Elasticsearch 是一個強大的搜索引擎,支持豐富的查詢語法,能夠滿足各種復雜的搜索需求。
基礎搜索語法
簡單搜索
最簡單的搜索方式是直接在指定的索引中搜索包含特定關鍵字的文檔。
GET /my_index/_search
{
"query": {
"match": {
"content": "Elasticsearch"
}
}
}
以上查詢會在 my_index 索引中搜索 content 字段中包含 "Elasticsearch" 的文檔。
匹配所有文檔
如果你想匹配索引中的所有文檔,可以使用 match_all 查詢。
GET /my_index/_search
{
"query": {
"match_all": {}
}
}
這個查詢會返回 my_index 中的所有文檔。
精確匹配 (Term Query)
精確查詢用于精確匹配指定字段的內容,適用于關鍵詞搜索。
GET /my_index/_search
{
"query": {
"term": {
"status": "active"
}
}
}
該查詢會返回 status 字段值為 active 的文檔。
組合查詢
布爾查詢 (Bool Query)
布爾查詢允許將多個查詢組合在一起。它支持 must、should、must_not 和 filter 子句,分別對應 AND、OR、NOT 和過濾條件。
GET /my_index/_search
{
"query": {
"bool": {
"must": [
{ "match": { "content": "Elasticsearch" } },
{ "term": { "status": "active" } }
],
"filter": [
{ "range": { "date": { "gte": "2024-01-01" } } }
]
}
}
}
此查詢會返回滿足以下條件的文檔:
-
content 字段包含 "Elasticsearch"。
-
status 字段為 active。
-
date 字段大于等于 "2024-01-01"。
范圍查詢 (Range Query)
范圍查詢允許你搜索數值、日期或其他可比較字段的范圍內的值。
GET /my_index/_search
{
"query": {
"range": {
"price": {
"gte": 100,
"lte": 200
}
}
}
}
這個查詢會返回 price 字段值在 100 到 200 之間的文檔。
多字段查詢
多字段匹配 (Multi-Match Query)
多字段查詢用于在多個字段中搜索相同的關鍵詞。
GET /my_index/_search
{
"query": {
"multi_match": {
"query": "Elasticsearch",
"fields": ["title", "content"]
}
}
}
這個查詢會在 title 和 content 字段中搜索 "Elasticsearch"。
字段存在查詢 (Exists Query)
存在查詢用于查找某個字段存在的文檔。
GET /my_index/_search
{
"query": {
"exists": {
"field": "user"
}
}
}
這個查詢會返回所有 user 字段存在的文檔。
排序與分頁
排序 (Sort)
你可以根據一個或多個字段對搜索結果進行排序。
GET /my_index/_search
{
"sort": [
{ "date": { "order": "desc" } },
{ "price": { "order": "asc" } }
],
"query": {
"match_all": {}
}
}
此查詢會先按 date 字段降序排序,再按 price 字段升序排序。
分頁 (Pagination)
分頁可以通過 from 和 size 參數來實現。
GET /my_index/_search
{
"from": 10,
"size": 5,
"query": {
"match_all": {}
}
}
這個查詢會跳過前 10 條記錄,并返回接下來的 5 條記錄。
高級搜索
嵌套查詢 (Nested Query)
如果文檔中包含嵌套對象或數組,nested 查詢可以用于對嵌套字段進行搜索。
GET /my_index/_search
{
"query": {
"nested": {
"path": "comments",
"query": {
"bool": {
"must": [
{ "match": { "comments.author": "John" } },
{ "range": { "comments.date": { "gte": "2024-01-01" } } }
]
}
}
}
}
}
此查詢會返回 comments 數組中包含 author 為 John 且 date 在 "2024-01-01" 之后的文檔。
高亮顯示 (Highlighting)
highlight 用于在搜索結果中突出顯示匹配的關鍵詞。
GET /my_index/_search
{
"query": {
"match": { "content": "Elasticsearch" }
},
"highlight": {
"fields": {
"content": {}
}
}
}
該查詢會在搜索結果中高亮顯示 content 字段中匹配到的 "Elasticsearch" 關鍵詞。
以上是一些Elasticsearch的基礎搜索語法示例,這些語法能夠幫助進行有效的數據查詢。根據實際業務需求,可以進一步組合這些查詢來實現更復雜的搜索功能。