### Example Setup - Index Creation Source: https://docs.opensearch.org/latest/api-reference/document-apis/update-document Provides an example of how to set up an index with sample documents for testing the Update API. ```APIDOC ## Example Setup ### Description Create an index with sample documents to follow along with the examples. ### Request Example #### PUT /sample-index1/_doc/1 ```json { "first_name": "Bruce", "last_name": "Wayne", "age": 35, "gadgets": [ "batarang" ] } ``` ### Request Example (Python Client) ```python response = client.index( index = "sample-index1", id = "1", body = { "first_name": "Bruce", "last_name": "Wayne", "age": 35, "gadgets": [ "batarang" ] } ) ``` ``` -------------------------------- ### Example New Container ID (os-node-03) Source: https://docs.opensearch.org/latest/migrate-or-upgrade/rolling-upgrade/rolling-upgrade-lab This is an example of the container ID returned after successfully starting the 'os-node-03' container. ```text d7f11726841a89eb88ff57a8cbecab392399f661a5205f0c81b60a995fc6c99d ``` -------------------------------- ### Install Sycamore with OpenSearch Connector Source: https://docs.opensearch.org/latest/tools/sycamore Install the Sycamore library with the OpenSearch connector using pip. This is the recommended way to get started with Sycamore for OpenSearch integration. ```bash pip install sycamore-ai[opensearch] ``` -------------------------------- ### Sample Program: Full Workflow Source: https://docs.opensearch.org/latest/clients/python-low-level A comprehensive example demonstrating client creation, index creation, document indexing, and printing responses. Note: Do not store credentials directly in code for production environments. ```python from opensearchpy import OpenSearch host = 'localhost' port = 9200 auth = ('admin', '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. # 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, ssl_assert_hostname = False, ssl_show_warn = False, ca_certs = ca_certs_path ) # Create an index with non-default settings. index_name = 'python-test-index' index_body = { 'settings': { 'index': { 'number_of_shards': 4 } } } response = client.indices.create(index=index_name, body=index_body) print('\nCreating index:') print(response) # Add a document to the index. document = { 'title': 'Moneyball', 'director': 'Bennett Miller', 'year': '2011' } id = '1' response = client.index( index = index_name, body = document, id = id, refresh = True ) print('\nAdding document:') print(response) ``` -------------------------------- ### GET /_search - Basic Completion Suggestion Source: https://docs.opensearch.org/latest/opensearch/supported-field-types/completion This example demonstrates how to query for suggestions that start with a specific prefix in a completion field. ```APIDOC ## GET /_search - Basic Completion Suggestion ### Description Queries the index for suggestions that start with a specified prefix in a completion field. ### Method GET ### Endpoint `//_search` ### Request Body ```json { "suggest": { "product-suggestions": { "prefix": "chess", "completion": { "field": "suggestions" } } } } ``` ### Response #### Success Response (200) Contains autocomplete suggestions, including the suggested text, score, and source document details. #### Response Example ```json { "took": 3, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 0, "relation": "eq" }, "max_score": null, "hits": [] }, "suggest": { "product-suggestions": [ { "text": "chess", "offset": 0, "length": 5, "options": [ { "text": "Chess set", "_index": "chess_store", "_type": "_doc", "_id": "2", "_score": 20.0, "_source": { "suggestions": [ { "input": "Chess set", "weight": 20 }, { "input": "Chess pieces", "weight": 10 }, { "input": "Chess board", "weight": 5 } ] } }, { "text": "Chess clock", "_index": "chess_store", "_type": "_doc", "_id": "3", "_score": 1.0, "_source": { "suggestions": [ "Chess clock", "Chess timer" ] } } ] } ] } } ``` ``` -------------------------------- ### Load Sample Configuration Source: https://docs.opensearch.org/latest/migration-assistant/playbooks Run this command to load the version-matched sample configuration before using a playbook. ```bash workflow configure sample --load ``` -------------------------------- ### Start Logstash with OpenSearch Output Source: https://docs.opensearch.org/latest/tools/logstash/index Starts Logstash in interactive mode, configured to read from stdin and output to an OpenSearch cluster. Ensure the OpenSearch host, user, and password match your setup. SSL verification is disabled for simplicity in this example. ```bash docker run -it --rm --name logstash --net test opensearchproject/logstash-oss-with-opensearch-output-plugin:7.16.2 -e 'input { stdin { } } output { opensearch { hosts => ["https://opensearch:9200"] index => "opensearch-logstash-docker-%{+YYYY.MM.dd}" user => "admin" password => "admin" ssl => true ssl_certificate_verification => false } }' ``` -------------------------------- ### Example of Listed Keystore Settings Source: https://docs.opensearch.org/latest/security/configuration/opensearch-keystore This output shows an example of settings that might be listed in an OpenSearch keystore. These typically include security-related configurations. ```bash keystore.seed plugins.security.ssl.http.pemkey_password_secure ``` -------------------------------- ### Retrieve All Context Management Configurations Source: https://docs.opensearch.org/latest/ml-commons-plugin/api/context-management-apis/list-context-management Use this GET request to fetch a list of all context management configurations within the cluster. No specific setup is required beyond having the ML plugin installed. ```http GET /_plugins/_ml/context_management ``` -------------------------------- ### Navigate to Demo Folder Source: https://docs.opensearch.org/latest/security/authentication-backends/saml Change the current directory to the demo folder within the downloaded SAML example repository. ```bash cd /demo ``` -------------------------------- ### Example Get Document Response Source: https://docs.opensearch.org/latest/api-reference/document-apis/get-documents This is an example of a successful response from a GET request to the OpenSearch Get Document API, showing the document's metadata and source. ```JSON { "_index": "products", "_id": "1", "_version": 1, "_seq_no": 0, "_primary_term": 1, "found": true, "_source": { "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" ] } } ``` -------------------------------- ### Load Version-Matched Sample Configuration Source: https://docs.opensearch.org/latest/migration-assistant/workflow-cli/getting-started Load a starter configuration file that matches the installed Migration Assistant release. This command reads the workflow schema and creates a base configuration file at `/root/.workflowUser.schema.json`. ```bash workflow configure sample --load ``` -------------------------------- ### Get Message by ID Example Request Source: https://docs.opensearch.org/latest/ml-commons-plugin/api/memory-apis/get-message Example of a GET request to retrieve a specific message using its ID. ```http GET /_plugins/_ml/memory/message/0m8ya40BfUsSoeNTj-pU ``` -------------------------------- ### Get All Messages within a Memory Example Request Source: https://docs.opensearch.org/latest/ml-commons-plugin/api/memory-apis/get-message Example of a GET request to retrieve all messages for a given memory ID. ```http GET /_plugins/_ml/memory/gW8Aa40BfUsSoeNTvOKI/messages ``` -------------------------------- ### Configure sample using workflow command Source: https://docs.opensearch.org/latest/migration-assistant/troubleshooting Use the workflow command to configure a sample setup after ensuring the .venv/bin directory is in your PATH. ```bash /.venv/bin/workflow configure sample ``` -------------------------------- ### Get Detector Example Request Source: https://docs.opensearch.org/latest/security-analytics/api-tools/detector-api Example GET request to fetch detector details. Replace `` with the ID of the detector you want to retrieve. ```http GET /_plugins/_security_analytics/detectors/ ``` -------------------------------- ### Example POST Request for Connector Search Source: https://docs.opensearch.org/latest/ml-commons-plugin/api/connector-apis/search-connector This example demonstrates how to search for connectors using a POST request with a `match_all` query and a specified size. ```json POST /_plugins/_ml/connectors/_search { "query": { "match_all": {} }, "size": 1000 } ``` -------------------------------- ### Example GET Response for Audit Configuration Source: https://docs.opensearch.org/latest/security/access-control/api This is an example response from a GET request to retrieve the audit configuration. It shows the structure of the configuration, including read-only fields. ```json { "_readonly" : [ "/audit/exclude_sensitive_headers", "/compliance/internal_config", "/compliance/external_config" ], "config" : { "compliance" : { "enabled" : true, "write_log_diffs" : false, "read_watched_fields" : { }, "read_ignore_users" : [ ], "write_watched_indices" : [ ], "write_ignore_users" : [ ], "read_metadata_only" : true, "write_metadata_only" : true, "external_config" : false, "internal_config" : true }, "enabled" : true, "audit" : { "ignore_users" : [ ], "ignore_requests" : [ ], "disabled_rest_categories" : [ "AUTHENTICATED", "GRANTED_PRIVILEGES" ], "disabled_transport_categories" : [ "AUTHENTICATED", "GRANTED_PRIVILEGES" ], "log_request_body" : true, "resolve_indices" : true, "resolve_bulk_requests" : true, "exclude_sensitive_headers" : true, "enable_transport" : true, "enable_rest" : true } } } ``` -------------------------------- ### Full OpenSearch Client Operations Example Source: https://docs.opensearch.org/latest/clients/javascript/index This comprehensive example demonstrates creating an OpenSearch client with SSL/TLS and authentication, creating an index with specific settings, adding, searching, updating, and deleting a document, and finally deleting the index. Ensure you replace placeholder credentials and paths with your actual configuration. ```javascript "use strict"; var host = "localhost"; var protocol = "https"; 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"; // Optional client certificates if you don't want to use HTTP basic authentication // var client_cert_path = '/full/path/to/client.pem' // var client_key_path = '/full/path/to/client-key.pem' // Create a client with SSL/TLS enabled var { Client } = require("@opensearch-project/opensearch"); var fs = require("fs"); var client = new Client({ node: protocol + "://" + auth + "@" + host + ":" + port, ssl: { ca: fs.readFileSync(ca_certs_path), // 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, }, }, }; var response = await client.indices.create({ index: index_name, body: settings, }); 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: index_name, body: document, refresh: true, }); console.log("Adding document:"); console.log(response.body); // Search for the document var query = { query: { match: { title: { query: "The Outsider", }, }, }, }; var response = await client.search({ index: index_name, body: query, }); console.log("Search results:"); console.log(JSON.stringify(response.body.hits, null, " ")); // Update a document var response = await client.update({ index: index_name, id: id, body: { doc: { genre: "Detective fiction", tv_adapted: true } }, refresh: true }); // Search for the updated document var query = { query: { match: { title: { query: "The Outsider", }, }, }, }; var response = await client.search({ index: index_name, body: query, }); console.log("Search results:"); console.log(JSON.stringify(response.body.hits, null, " ")); // Delete the document var response = await client.delete({ index: index_name, id: id, }); console.log("Deleting document:"); console.log(response.body); // Delete the index var response = await client.indices.delete({ index: index_name, }); console.log("Deleting index:"); console.log(response.body); } search().catch(console.log); ``` -------------------------------- ### Example Request for Get Message Traces API Source: https://docs.opensearch.org/latest/ml-commons-plugin/api/memory-apis/get-message-traces This example demonstrates how to call the Get Message Traces API to retrieve trace data for a given message ID. ```http GET /_plugins/_ml/memory/message/TAuCZY0BT2tRrkdmCPqZ/traces ``` -------------------------------- ### Explain Command with Simple Mode Source: https://docs.opensearch.org/latest/sql-and-ppl/ppl/commands/explain Displays only the logical plan tree without attributes. Requires the v3 engine to be enabled. ```ppl explain simple ``` -------------------------------- ### Initialize Go Module Source: https://docs.opensearch.org/latest/clients/go Create a new Go module for your project. ```bash go mod init ``` -------------------------------- ### Example Request for Workflow Status Source: https://docs.opensearch.org/latest/automating-configurations/api/get-workflow-status This is an example of a GET request to the workflow status endpoint. ```bash GET /_plugins/_flow_framework/workflow/8xL8bowB8y25Tqfenm50/_status ``` -------------------------------- ### Start OpenSearch Service Source: https://docs.opensearch.org/latest/opensearch/cluster Starts the OpenSearch service using systemd. Ensure OpenSearch is installed and configured as a service. ```bash sudo systemctl start opensearch.service ``` -------------------------------- ### Basic Join Syntax Examples Source: https://docs.opensearch.org/latest/sql-and-ppl/ppl/commands/join Demonstrates various ways to use the basic join command with different join types, join criteria (on/where), and aliasing. ```ppl source = table1 | inner join left = l right = r on l.a = r.a table2 | fields l.a, r.a, b, c ``` ```ppl source = table1 | inner join left = l right = r where l.a = r.a table2 | fields l.a, r.a, b, c ``` ```ppl source = table1 | left join left = l right = r on l.a = r.a table2 | fields l.a, r.a, b, c ``` ```ppl source = table1 | right join left = l right = r on l.a = r.a table2 | fields l.a, r.a, b, c ``` ```ppl source = table1 | full left = l right = r on l.a = r.a table2 | fields l.a, r.a, b, c ``` ```ppl source = table1 | cross join left = l right = r on 1=1 table2 ``` ```ppl source = table1 | left semi join left = l right = r on l.a = r.a table2 ``` ```ppl source = table1 | left anti join left = l right = r on l.a = r.a table2 ``` ```ppl source = table1 | join left = l right = r [ source = table2 | where d > 10 | head 5 ] ``` ```ppl source = table1 | inner join on table1.a = table2.a table2 | fields table1.a, table2.a, table1.b, table1.c ``` ```ppl source = table1 | inner join on a = c table2 | fields a, b, c, d ``` ```ppl source = table1 as t1 | join left = l right = r on l.a = r.a table2 as t2 | fields l.a, r.a ``` ```ppl source = table1 as t1 | join left = l right = r on l.a = r.a table2 as t2 | fields t1.a, t2.a ``` ```ppl source = table1 | join left = l right = r on l.a = r.a [ source = table2 ] as s | fields l.a, s.a ``` -------------------------------- ### Create Sample Index with Document Source: https://docs.opensearch.org/latest/api-reference/document-apis/update-document Use this to set up a sample index with a document for testing update operations. ```json PUT /sample-index1/_doc/1 { "first_name": "Bruce", "last_name": "Wayne", "age": 35, "gadgets": [ "batarang" ] } ``` ```python response = client.index( index = "sample-index1", id = "1", body = { "first_name": "Bruce", "last_name": "Wayne", "age": 35, "gadgets": [ "batarang" ] } ) ``` -------------------------------- ### Complete Sample Program with OpenSearch .NET Client Source: https://docs.opensearch.org/latest/clients/OSC-dot-net This program demonstrates indexing a single student, searching for a student by last name, performing a low-level search, and indexing multiple students. Ensure the OpenSearch client is initialized and the 'students' index exists. ```csharp using OpenSearch.Client; using OpenSearch.Net; 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"); Console.WriteLine("Searching for one student......"); SearchForOneStudent(); Console.WriteLine("Searching using low-level client......"); SearchLowLevel(); Console.WriteLine("Indexing an array of Student objects......"); 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 = 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}"); } } else { Console.WriteLine("Student not found."); } } } ``` -------------------------------- ### Start OpenSearch Dashboards (Tarball) Source: https://docs.opensearch.org/latest/security/configuration/disable-enable-security Command to start OpenSearch Dashboards after installation or configuration changes when using a tarball distribution. ```bash ./bin/opensearch-dashboards ``` -------------------------------- ### Install Plugin from Local File Source: https://docs.opensearch.org/latest/install-and-configure/plugins Installs a plugin by providing a local path to the plugin's zip file. Requires confirmation for additional permissions. ```bash sudo ./opensearch-plugin install file:/home/user/opensearch-anomaly-detection-2.2.0.0.zip ``` -------------------------------- ### Start OpenSearch after modifying jvm.options Source: https://docs.opensearch.org/latest/install-and-configure/configuring-opensearch/experimental Run this command to start OpenSearch after enabling feature flags in `config/jvm.options` for a tarball installation. ```bash ./bin/opensearch ``` -------------------------------- ### Display OpenSearch Benchmark Help Source: https://docs.opensearch.org/latest/benchmark/installing-benchmark After installation, use this command to view the available command-line options and usage information for OpenSearch Benchmark. ```bash opensearch-benchmark -h ``` -------------------------------- ### Example New Container ID Source: https://docs.opensearch.org/latest/migrate-or-upgrade/rolling-upgrade/rolling-upgrade-lab This is an example of the container ID returned after successfully starting a new OpenSearch node container. ```text 7b802865bd6eb420a106406a54fc388ed8e5e04f6cbd908c2a214ea5ce72ac00 ``` -------------------------------- ### Install OpenSearch Plugins Source: https://docs.opensearch.org/latest/install-and-configure/install-opensearch/operator/operator-opensearch-config Add plugin names or URLs to the `general.pluginsList` to install plugins for OpenSearch. This configuration is applied during cluster setup. ```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", ] ``` -------------------------------- ### Installation Source: https://docs.opensearch.org/latest/observing-your-data/agent-traces/instrument Install the base package and optional dependencies for specific providers. ```APIDOC ## Installation Install the base package: ``` pip install opensearch-genai-observability-sdk-py ``` To enable auto-instrumentation for specific providers, install the corresponding optional dependencies. For example, to instrument OpenAI and LangChain: ``` pip install opensearch-genai-observability-sdk-py[openai,langchain] ``` The following providers support auto-instrumentation: Provider | Package name ---|--- OpenAI | `openai` Anthropic | `anthropic` Amazon Bedrock | `bedrock` Google | `google` LangChain | `langchain` LlamaIndex | `llamaindex` ``` -------------------------------- ### Install uv using pip Source: https://docs.opensearch.org/latest/ai-agent-integrations/mcp-server/using Install the uv package, which provides the uvx command for running the server without a local installation. This is the recommended method. ```bash pip install uv ``` -------------------------------- ### Start OpenSearch Cluster with Docker Source: https://docs.opensearch.org/latest/ai-agent-integrations/agent-skills Starts a new OpenSearch cluster using Docker if no cluster is found. Assumes Docker is installed and configured. ```bash bash scripts/start_opensearch.sh ``` -------------------------------- ### Install All OpenSearch Agent Skills Source: https://docs.opensearch.org/latest/ai-agent-integrations/agent-skills Installs all available skills from the OpenSearch project. This is the command to run to get the full suite of agent skills. ```bash npx skills add opensearch-project/opensearch-agent-skills ``` -------------------------------- ### Install Base Package Source: https://docs.opensearch.org/latest/observing-your-data/agent-traces/instrument Install the core SDK package using pip. ```bash pip install opensearch-genai-observability-sdk-py ``` -------------------------------- ### Example Response for Get Account Details Source: https://docs.opensearch.org/latest/security/access-control/api An example JSON response showing the details of an account, including username, roles, and tenant access. ```json { "user_name": "admin", "is_reserved": true, "is_hidden": false, "is_internal_user": true, "user_requested_tenant": null, "backend_roles": [ "admin" ], "custom_attribute_names": [], "tenants": { "global_tenant": true, "admin_tenant": true, "admin": true }, "roles": [ "all_access", "own_index" ] } ``` -------------------------------- ### Start OpenSearch with Security Enabled Source: https://docs.opensearch.org/latest/install-and-configure/install-opensearch/tar Run the OpenSearch startup script to launch the cluster with the security demo configuration. This command assumes default settings. ```bash ./opensearch-tar-install.sh ``` -------------------------------- ### Install Multiple OpenSearch Plugins Source: https://docs.opensearch.org/latest/install-and-configure/install-opensearch/plugins Installs multiple plugins in a single command. List plugin names separated by spaces. ```bash $ sudo ./opensearch-plugin install analysis-nori repository-s3 ``` -------------------------------- ### Regexp Query Example Source: https://docs.opensearch.org/latest/query-dsl/term/regexp This example demonstrates how to use the regexp query to find terms starting with an uppercase or lowercase letter followed by 'amlet'. ```APIDOC ## GET shakespeare/_search ### Description Searches for terms in the `play_name` field that match the regular expression `[a-zA-Z]amlet`. ### Method GET ### Endpoint `/shakespeare/_search` ### Query Parameters - **query** (object) - Required - The query definition. - **regexp** (object) - Required - The regexp query definition. - **play_name** (object) - Required - The field to search within. - **value** (string) - Required - The regular expression pattern. - **boost** (float) - Optional - A floating-point value that specifies the weight of this field toward the relevance score. Default is 1.0. - **case_insensitive** (boolean) - Optional - If true, allows case-insensitive matching. Default is false. - **flags** (string) - Optional - Enables optional operators for Lucene’s regular expression engine. - **max_determinized_states** (integer) - Optional - Specifies the maximum number of automaton states the query requires. Default is 10,000. - **rewrite** (string) - Optional - Determines how OpenSearch rewrites and scores multi-term queries. Default is `constant_score`. ### Request Example ```json { "query": { "regexp": { "play_name": "[a-zA-Z]amlet" } } } ``` ### Response #### Success Response (200) - **took** (integer) - Time in milliseconds for the search to execute. - **timed_out** (boolean) - Indicates if the request timed out. - **hits** (object) - Contains the search results. - **total** (object) - Information about the total number of hits. - **value** (integer) - The total number of hits. - **relation** (string) - The relation of the total value to the number of hits (e.g., 'eq' for equal). - **max_score** (float) - The maximum score for this query. - **hits** (array) - An array of search hit objects. - **_index** (string) - The name of the index. - **_id** (string) - The ID of the document. - **_score** (float) - The score of the document. - **_source** (object) - The source fields of the document. - **play_name** (string) - The name of the play. - **line_id** (integer) - The ID of the line. - **line_number** (integer) - The line number. - **speaker** (string) - The speaker of the line. - **text_entry** (string) - The text of the line. #### Response Example ```json { "took": 5, "timed_out": false, "hits": { "total": { "value": 1, "relation": "eq" }, "max_score": 1.0, "hits": [ { "_index": "shakespeare", "_id": "_aBcDeF", "_score": 1.0, "_source": { "play_name": "Hamlet", "line_id": 1, "line_number": 1, "speaker": "Enter Ghost", "text_entry": "" } } ] } } ``` ``` -------------------------------- ### Example Workspace Object Configuration Source: https://docs.opensearch.org/latest/dashboards/workspace/workspace Illustrates a typical workspace object configuration, demonstrating the use of ID, name, description, and features. ```json { id: "M5NqCu", name: "Analytics team", description: "Analytics team workspace", features: ["use-case-analytics"] } ``` -------------------------------- ### LangChain Single-Agent Setup Source: https://docs.opensearch.org/latest/ai-agent-integrations/mcp-server/using Connect to LangChain for a single-agent setup using MultiServerMCPClient and create a tool-calling agent. Ensure necessary packages are installed. ```python import asyncio from langchain_mcp_adapters.client import MultiServerMCPClient from langchain_openai import ChatOpenAI from langchain.agents import create_tool_calling_agent, AgentExecutor from langchain_core.prompts import ChatPromptTemplate async def main(): async with MultiServerMCPClient({ "opensearch": { "transport": "stdio", "command": "uvx", "args": ["opensearch-mcp-server-py"], "env": { "OPENSEARCH_URL": "http://localhost:9200", "OPENSEARCH_USERNAME": "admin", "OPENSEARCH_PASSWORD": "admin", "OPENSEARCH_SSL_VERIFY": "false", }, } }) as mcp_client: tools = mcp_client.get_tools() llm = ChatOpenAI(model="gpt-4o") prompt = ChatPromptTemplate.from_messages([ ("system", "You are a helpful assistant with access to OpenSearch tools."), ("human", "{input}"), ("placeholder", "{agent_scratchpad}"), ]) agent = create_tool_calling_agent(llm, tools, prompt) agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True) await agent_executor.ainvoke({"input": "How many documents are in the 'orders' index?"}) asyncio.run(main()) ``` -------------------------------- ### POST /products/_search with Wrapper Query Source: https://docs.opensearch.org/latest/query-dsl/specialized/wrapper This example demonstrates how to use the `wrapper` query to execute a search request with a Base64-encoded query. It first shows the index creation and bulk indexing for context, then the encoding of a match query, and finally the execution of the search using the wrapper. ```APIDOC ## Create Index ### Description Creates an index named `products` with a simple text mapping for the `title` field. ### Method PUT ### Endpoint `/products` ### Request Body ```json { "mappings": { "properties": { "title": { "type": "text" } } } } ``` ## Index Sample Documents ### Description Indexes three sample documents into the `products` index using the bulk API. ### Method POST ### Endpoint `/products/_bulk` ### Request Body ```json { "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" } ``` ## Encode Search Query ### Description Encodes a JSON search query for the `title` field containing the term `headphones` into Base64 format. ### Method Shell command (example) ### Command ```bash echo -n '{ "match": { "title": "headphones" } }' | base64 ``` ### Output ``` eyAibWF0Y2giOiB7ICJ0aXRsZSI6ICJoZWFkcGhvbmVzIiB9IH0= ``` ## Execute Encoded Query with Wrapper ### Description Executes a search query using the `wrapper` parameter, which accepts a Base64-encoded JSON query. This example searches for documents where the `title` contains `headphones`. ### Method POST ### Endpoint `/products/_search` ### Request Body ```json { "query": { "wrapper": { "query": "eyAibWF0Y2giOiB7ICJ0aXRsZSI6ICJoZWFkcGhvbmVzIiB9IH0=" } } } ``` ### Response (Success - 200) #### Description Returns the search results, including matching documents and hit information. #### Response Body Example ```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" } } ] } } ``` ``` -------------------------------- ### Install Python 3.7 and Setup Virtual Environment on Ubuntu Source: https://docs.opensearch.org/latest/ml-commons-plugin/gpu-acceleration Installs Python 3.7 and its venv module, then creates and activates a Python virtual environment for installing Neuron pip packages. Requires g++. ```bash sudo add-apt-repository ppa:deadsnakes/ppa sudo apt-get install python3.7 cd ~ sudo apt-get install -y python3.7-venv g++ python3.7 -m venv pytorch_venv source pytorch_venv/bin/activate pip install -U pip ``` -------------------------------- ### Start Docker Compose for SAML Demo Source: https://docs.opensearch.org/latest/security/authentication-backends/saml Initiate the OpenSearch, OpenSearch Dashboards, and SAML server instances using Docker Compose. ```bash docker compose up. ``` -------------------------------- ### Example Snapshot Response Source: https://docs.opensearch.org/latest/api-reference/snapshots/get-snapshot This is an example of a successful response from the Get Snapshot API, detailing the properties of a snapshot, including its state, indices, and shard information. ```json { "snapshots" : [ { "snapshot" : "my-first-snapshot", "uuid" : "3P7Qa-M8RU6l16Od5n7Lxg", "version_id" : 136217927, "version" : "2.0.1", "indices" : [ ".opensearch-observability", ".opendistro-reports-instances", ".opensearch-notifications-config", "shakespeare", ".opendistro-reports-definitions", "opensearch_dashboards_sample_data_flights", ".kibana_1" ], "data_streams" : [ ], "include_global_state" : true, "state" : "SUCCESS", "start_time" : "2022-08-11T20:30:00.399Z", "start_time_in_millis" : 1660249800399, "end_time" : "2022-08-11T20:30:14.851Z", "end_time_in_millis" : 1660249814851, "duration_in_millis" : 14452, "failures" : [ ], "shards" : { "total" : 7, "failed" : 0, "successful" : 7 } } ] } ``` -------------------------------- ### List Available Skills Before Installation Source: https://docs.opensearch.org/latest/ai-agent-integrations/agent-skills Displays a list of all available skills using the `--list` flag before proceeding with installation. This allows you to review options before committing to an installation. ```bash npx skills add opensearch-project/opensearch-agent-skills --list ``` -------------------------------- ### Example Request to Search Threat Intelligence Findings Source: https://docs.opensearch.org/latest/security-analytics/threat-intelligence/api/findings This example demonstrates how to make a GET request to the findings endpoint, specifying a maximum of 3 results to be returned. ```http GET /_plugins/_security_analytics/threat_intel/findings/_search?size=3 ``` -------------------------------- ### Explain Command with Standard Mode Source: https://docs.opensearch.org/latest/sql-and-ppl/ppl/commands/explain Shows the logical and physical plan with pushdown information using the standard explain mode. This is the default mode and works with both v2 and v3 engines. ```ppl explain standard ``` -------------------------------- ### Example Request to Retrieve All Query Insights Settings Source: https://docs.opensearch.org/latest/observing-your-data/query-insights/settings-api This is an example of a GET request to retrieve all query insights settings. It demonstrates the basic structure for querying the API. ```bash GET /_insights/settings/ ``` -------------------------------- ### Initialize OpenSearch Client Source: https://docs.opensearch.org/latest/clients/php Sets up the OpenSearch client with connection details and authentication. Disables SSL verification for local development. ```php client = (new \OpenSearch\GuzzleClientFactory())->create([ 'base_uri' => 'https://localhost:9200', 'auth' => ['admin', getenv('OPENSEARCH_PASSWORD')], 'verify' => false, // Disables SSL verification for local development. ]); } // Create an index with non-default settings. public function createIndex() { $this->client->indices()->create([ 'index' => INDEX_NAME, 'body' => [ 'settings' => [ 'index' => [ 'number_of_shards' => 4 ] ] ] ]); } public function info() { // Print OpenSearch version information on console. var_dump($this->client->info()); } // Create a document public function create() { $time = time(); $this->existingID = $time; $this->deleteID = $time . '_uniq'; // Create a document passing the id $this->client->create([ 'id' => $time, 'index' => INDEX_NAME, 'body' => $this->getData($time) ]); // Create a document passing the id $this->client->create([ 'id' => $this->deleteID, 'index' => INDEX_NAME, 'body' => $this->getData($time) ]); // Create a document without passing the id (will be generated automatically) $this->client->create([ 'index' => INDEX_NAME, 'body' => $this->getData($time + 1) ]); //This should throw an exception because ID already exists // $this->client->create([ // 'id' => $this->existingID, // 'index' => INDEX_NAME, // 'body' => $this->getData($this->existingID) // ]); } public function update() { $this->client->update([ 'id' => $this->existingID, 'index' => INDEX_NAME, 'body' => [ //data must be wrapped in 'doc' object 'doc' => ['name' => 'updated'] ] ]); } public function bulk() { $bulkData = []; $time = time(); for ($i = 0; $i < 20; $i++) { $id = ($time + $i) . rand(10, 200); $bulkData[] = [ 'index' => [ '_index' => INDEX_NAME, '_id' => $id, ] ]; $this->bulkIds[] = $id; $bulkData[] = $this->getData($time + $i); } //will not throw exception! check $response for error $response = $this->client->bulk([ //default index 'index' => INDEX_NAME, 'body' => $bulkData ]); //give elastic a little time to create before update sleep(2); // bulk update for ($i = 0; $i < 15; $i++) { $bulkData[] = [ 'update' => [ '_index' => INDEX_NAME, '_id' => $this->bulkIds[$i], ] ]; $bulkData[] = [ 'doc' => [ 'name' => 'bulk updated' ] ]; } //will not throw exception! check $response for error $response = $this->client->bulk([ //default index 'index' => INDEX_NAME, 'body' => $bulkData ]); } public function deleteByQuery(string $query) { if ($query == '') { return; } $this->client->deleteByQuery([ 'index' => INDEX_NAME, 'q' => $query ]); } // Delete a single document public function deleteByID() { $this->client->delete([ 'id' => $this->deleteID, 'index' => INDEX_NAME, ]); } public function search() { $docs = $this->client->search([ //index to search in or '_all' for all indices 'index' => INDEX_NAME, 'size' => 1000, 'body' => [ 'query' => [ 'prefix' => [ 'name' => 'wrecking' ] ] ] ]); var_dump($docs['hits']['total']['value'] > 0); // Search for it $docs = $this->client->search([ 'index' => INDEX_NAME, 'body' => [ 'size' => 5, 'query' => [ ``` -------------------------------- ### Example Response for Get Stored Script Source: https://docs.opensearch.org/latest/api-reference/script-apis/get-stored-script This is an example of the JSON response when retrieving a stored script. It includes the script's ID, language, and source code. ```json { "_id" : "my-first-script", "found" : true, "script" : { "lang" : "painless", "source" : """ int total = 0; for (int i = 0; i < doc['ratings'].length; ++i) { total += doc['ratings'][i]; } return total; " } } ``` -------------------------------- ### Start Docker Compose Source: https://docs.opensearch.org/latest/security/configuration/saml Launch the OpenSearch, OpenSearch Dashboards, and SAML server nodes defined in the docker-compose.yml file. ```bash $ docker compose up ```