OpenSearch SQL

repository·main·Indexed 41 days ago

https://github.com/opensearch-project/sql

A plugin that enables querying OpenSearch data using SQL or Piped Processing Language (PPL) syntax. It includes the Unified Query API for parsing, planning, and compiling queries into Calcite logical plans or JDBC PreparedStatements, as well as the ppl-rest-spi for integrating custom read-only data as queryable tables.

Tokens
205.1K
Snippets
785
Records
1K
Agent score
48%

What's inside OpenSearch SQL

  1. Overview of the Federated PPL Query Engine

    main

    The Federated PPL Query Engine allows users to execute Piped Processing Language (PPL) queries across multiple, heterogeneous data sources. While PPL was traditionally limited to OpenSearch, this framework enables observability solutions (like Event Explorer, Notebooks, and Trace Analytics) to leverage data from external metric stores such as Prometheus and AWS CloudWatch.

    Key capabilities include:

    • Querying data from multiple configured data sources using a single PPL interface.
    • Correlating metrics and logs from different data sources.
    • Injecting data from various sources into ML commands.

    Limitations:

    • No Cross-Datasource Joins: Join queries spanning different data sources are currently out of scope.
    • Single Node Execution: Distributed query execution is not supported; all execution occurs on a single coordination node.
  2. Overview of PPL built-in functions

    main

    PPL (Piped Processing Language) supports a wide range of built-in functions for data processing and analysis. These functions are categorized by their purpose, allowing you to manipulate, transform, and aggregate data within your PPL queries.

    Function Categories

    • Aggregation functions: Used for summarizing data (e.g., COUNT, SUM, AVG, MAX, MIN, DISTINCT_COUNT).
    • Collection functions: For working with arrays and multi-valued fields (e.g., ARRAY, FILTER, TRANSFORM, MVJOIN).
    • Conditional functions: For logic and null handling (e.g., IF, CASE, COALESCE, ISNULL, IFNULL).
    • Type conversion functions: For changing data types (e.g., CAST, TOSTRING, TONUMBER).
    • Cryptographic functions: For hashing (e.g., MD5, SHA1, SHA2).
    • Date and time functions: For temporal manipulation (e.g., DATE_FORMAT, NOW, DATEDIFF, EXTRACT).
    • Expressions: Includes arithmetic and predicate operators.
    • IP address functions: For network data (e.g., CIDRMATCH, GEOIP).
    • JSON functions: For interacting with JSON documents (e.g., JSON_EXTRACT, JSON_SET, JSON_ARRAY).
    • Mathematical functions: For complex calculations (e.g., SQRT, POW, ROUND, SIN).
    • Relevance functions: For full-text search scoring (e.g., MATCH, MULTI_MATCH, QUERY_STRING).
    • Statistical functions: For basic statistics (e.g., MAX, MIN).
    • String functions: For text manipulation (e.g., CONCAT, SUBSTRING, UPPER, REGEXP_REPLACE).
    • System functions: For inspecting metadata (e.g., TYPEOF).
  3. Overview of OpenSearch SQL and PPL

    main

    OpenSearch SQL allows you to extract insights from your data using standard SQL or the Piped Processing Language (PPL) syntax. You can use common SQL features like aggregations, group by, and where clauses to investigate data. Results can be read as either JSON documents or CSV tables, providing flexibility for different downstream workflows.

    Key capabilities include:

    • Basic filtering and aggregation.
    • Complex queries: semi-structured data querying, JOINs, set operations, and sub-queries.
    • Specialized OpenSearch functions for advanced analytics and visualization.
  4. Overview of OpenSearch SQL

    main
    OpenSearch SQL allows you to extract insights from OpenSearch clusters using standard SQL query syntax. It provides a familiar interface for querying data without needing to learn the underlying OpenSearch Query DSL. The documentation covers interfaces, administration, language structure (identifiers, data types, values), Data Query Language (DQL) including complex queries and aggregations, and advanced features like Vector Search and PartiQL (JSON) support.
  5. Overview of the async-query-core library

    main
    The async-query-core library implements the core logic for asynchronous queries. It is designed with extension points that allow consumers to provide custom implementations for different data storage backends and other system components. While this library provides the core logic, the async-query module specifically provides implementations based on OpenSearch indices.
  6. New features in SQL Engine V2

    main

    The SQL Engine V2 introduces significant improvements in language support, query complexity, and advanced features compared to the previous engine. Key additions include:

    Language & Data Types

    • Identifiers: Support for names containing special characters.
    • Data Types: Support for date and interval types.
    • Expressions: Support for complex nested expressions.
    • Comments: Standard SQL comment support.
    • SQL Functions: Expanded date function support including ADDDATE, DATE_ADD, DATE_SUB, DAY, DAYNAME, DAYOFMONTH, DAYOFWEEK, DAYOFYEAR, FROM_DAYS, HOUR, MICROSECOND, MINUTE, QUARTER, SECOND, SUBDATE, TIME, TIME_TO_SEC, TO_DAYS, and WEEK.

    Query Capabilities

    • Basic Queries: HAVING without a GROUP BY clause, aggregation over arbitrary expressions, ordering by NULLS FIRST/LAST, and ordering by aggregate functions.
    • Complex Queries: Subqueries in the FROM clause with support for arbitrary nesting and aggregation.
    • Advanced Features: Window functions (ranking and aggregate) and selective aggregation using the standard FILTER function.

    OpenSearch Specifics

    • Semi-structured Data: Support for querying OpenSearch object fields at arbitrary levels.
    • Multi-fields: Automatic handling of multi-fields (e.g., text is automatically converted to text.keyword).
  7. New PPL commands available in the V3 engine

    main

    The V3 engine (Calcite integration) focuses on enhancing the PPL language. In the initial 3.0.0 release, the following new commands were introduced to improve query capabilities:

    • Join: For joining datasets.
    • Lookup: For performing lookups.
    • Subquery: For executing subqueries within PPL.
  8. Integrate custom data into PPL via ppl-rest-spi

    main

    The ppl-rest-spi is a Service Provider Interface (SPI) that allows OpenSearch plugins to contribute read-only data as queryable tables in PPL using the rest '<name>' command.

    Key characteristics:

    • No Grammar Changes: You don't need to add new PPL commands or keywords.
    • Composition: Contributed endpoints compose with standard PPL pipes like | where, | stats, and | head.
    • Type Safety: To avoid cross-classloader issues, the SPI exchanges row values as plain java.lang types. Every endpoint surfaces a single response column containing a serialized JSON string. Users then use spath or json_extract to pull specific fields and cast() to convert them to numeric types if needed.
  9. What is Piped Processing Language (PPL)?

    main

    Piped Processing Language (PPL) is a query language used in OpenSearch for data exploration and discovery. It uses a sequence of commands delimited by pipes (|) to process data and return results. PPL is designed as a human-friendly interface for ad hoc queries, making it easier to explore log, monitoring, and observability data compared to the more complex Query DSL.

    Queries typically start with a search command, followed by a series of processing commands.

    source=accounts
    | where age > 18
    | fields firstname, lastname
  10. What is the QueryService and how does it relate to QueryManager?

    main

    While QueryManager is the high-level interface, QueryService is the low-level interface of the core engine.

    Each Plan is responsible for deciding how to execute a query by using the QueryService to perform the following tasks:

    • Analyze the query
    • Plan the execution
    • Optimize the query
    • Execute the query
  11. Overview of OpenSearch SQL Cursor (Pagination) Support

    main

    OpenSearch SQL provides cursor support to enable traversal over large result sets on a page-by-page basis. This is a fundamental requirement for SQL engines to avoid loading entire result sets into memory and to bypass the default OpenSearch limit of 10,000 documents (controlled by index.max_result_window).

    Key Use Cases

    • Bypassing Result Limits: Allows users to retrieve more than the default 10,000 documents without manually adjusting index.max_result_window.
    • Web Interfaces: Enables tools like OpenSearch Dashboards to skim through large result sets via pagination.
    • BI and Batch Processing: Facilitates full result set loading for analysis via JDBC/ODBC drivers.

    Implementation Roadmap

    • Phase I: Supports SELECT queries for JDBC and ODBC drivers (and SQL CLI).
    • Phase II: Adds support for SELECT with GROUP BY (aggregation queries).
    • Phase III: Adds support for EQUI-JOINS and text-based formats like CSV and RAW (pipe separated).
  12. Understand V3 Script Queries

    main

    V3 scripts use a Calcite expression tree encoded as a base64 string. To improve cache hit ratios, the expression tree is standardized (e.g., replacing field names and literals with placeholders like ?i) and specific information is moved into a params object.

    When using V3 scripts, the lang must be set to opensearch_compounded_script and the source JSON must include "langType":"calcite".

    {
        "script": {
            "source": "{\"langType\":\"calcite\", \"script\":\"<V3_SCRIPT_ENCODED_BYTE_STRING>\"}",
            "lang": "opensearch_compounded_script",
            "params": {
                "utcTimestamp": 17630261838681530000,
                "SOURCES": [0, 2, 2, 1],
                "DIGESTS": ["age", 35, "u35", "email"]
            }
        }
    }