



简介

GET /my_index/_search{"query": {"bool": {"must": [{ "match": { "title": "example" } },{"bool": {"should": [{ "term": { "category": "electronics" } },{ "term": { "category": "gadgets" } }]}}],"filter": {"range": {"price": { "gte": 30, "lte": 150 }}}}},"aggs": {"average_price_per_category": {"terms": {"field": "category","size": 5},"aggs": {"average_price": {"avg": {"field": "price"}}}}}}

SELECT title, category, priceFROM my_indexWHERE title = 'example'AND (category = 'electronics' OR category = 'gadgets')AND price BETWEEN 30 AND 150GROUP BY categoryORDER BY AVG(price) DESCLIMIT 5;


创建索引
PUT /my_index{"mappings": {"properties": {"title": { "type": "text" },"category": { "type": "keyword" },"price": { "type": "float" }}}}
插入数据
POST /my_index/_doc/1{"title": "Elasticsearch Guide","category": "electronics","price": 99.99}POST /my_index/_doc/2{"title": "Smart Gadget","category": "gadgets","price": 45.00}POST /my_index/_doc/3{"title": "Kibana Insights","category": "electronics","price": 75.50}
查询所有数据
GET /my_index/_search{}
使用 SQL 查询
POST /_sql?format=txt{"query": "SELECT * FROM my_index"}
返回结果类似数据库表格形式,显得更为清晰。
常见 SQL 查询示例
POST /_sql?format=txt{"query": "SELECT * FROM my_index LIMIT 1"}
POST /_sql?format=txt{"query": "SELECT * FROM my_index ORDER BY price DESC"}
POST /_sql?format=txt{"query": "SELECT category, COUNT(1) FROM my_index GROUP BY category"}
POST /_sql?format=txt{"query": "SELECT SUM(price) FROM my_index"}
POST /_sql?format=txt{"query": "SELECT * FROM my_index WHERE price = '45.00'"}
处理时间字段
POST /my_index/_doc/4{"title": "Advanced Elasticsearch","category": "electronics","price": 60.00,"create_date": "2023-11-01T12:00:00.123"}
POST /_sql?format=txt{"query": "SELECT title, DATETIME_FORMAT(create_date, 'YYYY-MM-dd') AS date FROM my_index WHERE category = 'electronics'"}
字符串操作
POST /_sql?format=txt{"query": "SELECT SUBSTRING(category, 1, 3) AS SubstringValue FROM my_index"}
总结


Elasticsearch 官方下载:
https://www.elastic.co/cn/downloads
Elasticsearch SQL 文档:
https://www.elastic.co/guide/en/elasticsearch/reference/8.9/sql-overview.html






- End -
原文作者:IT枫斗者;如有侵权,请联系管理员删除。