Loading SQL to Elasticsearch Converter...
Please wait a moment

From a SQL SELECT to an Elasticsearch search request

If you think in SQL but the data lives in Elasticsearch, paste the query above and you get the Query DSL request that returns the same documents. WHERE turns into bool filters, GROUP BY into aggregations, and anything a search can't do the same way is spelled out in a note above the request.

How to Convert SQL to Elasticsearch, Step by Step

Step 1

Paste a SQL SELECT

Write the query the way you would for a database table. The table name is used as the index name, and a column like address.city is read as a field path inside the document.

•
Paste: one or more SELECT statements, separated by ;
•
Upload: a .sql or .txt file
•
Sample: a blog search with IN, a date range, LIKE, ORDER BY and LIMIT

Example: products with a filter, an OR and a sort

SELECT name, price
FROM products
WHERE category = 'electronics'
  AND price > 50
  AND (brand = 'Acme' OR rating >= 4.5)
ORDER BY price ASC
LIMIT 20
Step 2

Read the converted request

Each clause maps to the part of the request that does the same job. SQL treats NULL as "unknown", and so does the output: status <> 'old' doesn't return documents without a status.

•
Columns: the SELECT list becomes _source; * returns everything
•
Conditions: = → term, < <= > >= and BETWEEN → range, IN → terms, IS NULL → no exists
•
Logic: AND → filter, OR → should, NOT → must_not, with brackets and precedence kept
•
Paging: ORDER BY → sort, LIMIT → size, OFFSET → from

Output for the example above

# Note: Elasticsearch sorts documents without the field last in both directions. Add "missing": "_first" if your database puts NULLs first.
# Note: term, terms, prefix and wildcard compare the exact stored value. For text fields use the keyword sub-field (for example "name.keyword").
GET /products/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "category": "electronics"
          }
        },
        {
          "range": {
            "price": {
              "gt": 50
            }
          }
        },
        {
          "bool": {
            "should": [
              {
                "term": {
                  "brand": "Acme"
                }
              },
              {
                "range": {
                  "rating": {
                    "gte": 4.5
                  }
                }
              }
            ],
            "minimum_should_match": 1
          }
        }
      ]
    }
  },
  "_source": [
    "name",
    "price"
  ],
  "sort": [
    {
      "price": {
        "order": "asc"
      }
    }
  ],
  "size": 20
}
Step 3

Check field mappings

A database compares strings exactly, and so do term, prefix and wildcard, but only on keyword fields. If your index stores name as analysed text, point the query at name.keyword. GROUP BY queries become terms aggregations, which also need keyword or numeric fields.

Example: revenue per category, only busy categories

SELECT category, COUNT(*) AS orders, SUM(amount) AS revenue
FROM orders
WHERE status = 'completed'
GROUP BY category
HAVING COUNT(*) > 10
ORDER BY revenue DESC

Output

# Note: COUNT(*) per group is the doc_count of each bucket.
# Note: Each terms aggregation returns at most "size" buckets (10,000 here). For more groups, page with a composite aggregation.
# Note: term, terms, prefix and wildcard compare the exact stored value. For text fields use the keyword sub-field (for example "name.keyword").
GET /orders/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "status": "completed"
          }
        }
      ]
    }
  },
  "size": 0,
  "aggs": {
    "by_category": {
      "terms": {
        "field": "category",
        "size": 10000,
        "order": {
          "revenue": "desc"
        }
      },
      "aggs": {
        "revenue": {
          "sum": {
            "field": "amount"
          }
        },
        "having": {
          "bucket_selector": {
            "buckets_path": {
              "v0": "_count"
            },
            "script": "params.v0 > 10"
          }
        }
      }
    }
  }
}
Step 4

Copy or download

The output is written for the Kibana Dev Tools console: paste it in and run it. The # Note: lines are comments there, so you can leave them in while you check them.

Frequently Asked Questions

Which SQL does it understand?

One or more SELECT statements on a single table: a column list or *, WHERE with =, <>, !=, <, <=, >, >=, IN, NOT IN, BETWEEN, LIKE, ILIKE, IS NULL and IS NOT NULL joined by AND, OR, NOT and brackets, GROUP BY with COUNT, SUM, AVG, MIN and MAX, HAVING, ORDER BY, LIMIT and OFFSET (also MySQL LIMIT 5, 10, SQL Server TOP and FETCH FIRST). Single quotes, '' inside strings, "quoted", `backtick` and [bracket] names, comments and a trailing semicolon are all fine.

How is WHERE turned into a bool query?

Every condition goes into a non-scoring bool filter. = becomes term, the comparison operators become range, IN becomes terms and BETWEEN becomes one range with gte and lte. AND keeps its higher precedence over OR, so a OR b AND c is read as a OR (b AND c), and OR becomes should with minimum_should_match 1. A missing field counts as NULL, so price <> 10 and NOT IN also require the field to exist, the same way SQL skips NULL rows.

What happens to SQL that has no Elasticsearch equivalent?

It is not dropped silently. Functions such as LOWER() in WHERE, arithmetic and comparisons between two columns are left out of the query and named in a "# Note:" line, which means the search can return more documents than the SQL would. JOINs, UNION, subqueries, window functions and INSERT, UPDATE or DELETE stop with a message, because one Elasticsearch search can't do them.

How do LIKE patterns convert?

A pattern with only a trailing % becomes a prefix query, other patterns become a wildcard query with % as * and _ as ?, and a pattern without wildcards becomes a term. Characters Elasticsearch treats specially, such as * and ?, are escaped, and ESCAPE (or a backslash) works for a literal % or _. The result is case-sensitive; write ILIKE to get "case_insensitive": true.

How do GROUP BY and HAVING work?

Each GROUP BY column becomes a terms aggregation, one nested inside the other, and SUM, AVG, MIN, MAX and COUNT(column) become metric aggregations in the innermost bucket. COUNT(*) is the doc_count every bucket already has. ORDER BY sorts the buckets, LIMIT sets how many come back, and HAVING becomes a bucket_selector script. COUNT(DISTINCT column) becomes a cardinality aggregation, which is an estimate.

Are long IDs and decimals kept exactly?

Yes. The JSON body is written from the text of your query, so an ICCID like 8901240544102066246 stays a bare number with every digit, 14.50 stays 14.50, and a quoted '00501' stays the string "00501".

Can I paste the output into Kibana?

Yes. The output is in Kibana Dev Tools format: any "# Note:" comment lines, a GET /index/_search (or _count) line and the JSON body. The table name becomes the index name, lowercased if needed. Several statements give several requests, one after another. Download saves the same text as a .txt file.

Is my query sent anywhere?

No. The conversion runs in your browser, the query is not uploaded, and nothing is kept: a reload starts with an empty editor.

Going the other way? Try Elasticsearch to SQL. For other targets there is SQL to MongoDB and SQL to DynamoDB, and the Elasticsearch query formatter tidies a request you already have.