一、入門
使用Elasticsearch的第一步是啟動Elasticsearch進程,並將API調用發送到它所在的默認端口9200。我們可以通過簡單的HTTP GET請求來檢索有關我們所創建的節點及其狀態的信息:
curl -X GET "localhost:9200/"
在響應中,我們可以看到版本號和集群名稱等節點信息。現在我們可以使用類似以下命令來測試集群的運行狀態:
curl -XGET 'localhost:9200/_cluster/health?pretty'
該請求返回有關群集狀態的信息。您可以在
了解更多信息。
二、索引和搜索
索引和搜索是Elasticsearch API的核心,它們允許您存儲和檢索大量結構化和非結構化數據。創建索引最簡單的方法是使用curl。
curl -X PUT 'localhost:9200/index_name?pretty'
然後您可以通過以下方式將文檔添加到索引中:
curl -X PUT 'localhost:9200/index_name/_doc/1?pretty' -d' { "title": "Hello World!", "content": "This is my first Elasticsearch document." }'
1. 索引API
以下是索引API的示例,其中我們使用html實體化來避免瀏覽器對html標籤的解析。
curl -X PUT 'localhost:9200/<em>my_index</em>&pretty' -H 'Content-Type: application/json' -d' { "settings": { "number_of_shards": 1, "number_of_replicas": 0 } }'
2. 搜索API
Elasticsearch提供了各種搜索API,例如match_all、match、term和bool查詢等。以下是一個簡單的查詢示例:
curl -X GET 'localhost:9200/my_index/_search?q=title:Hello&pretty'
三、聚合和過濾
Elasticsearch API還提供了聚合和過濾的功能,可以對搜索結果進行高級操作和計算。以下是一個範圍聚合的示例:
curl -X GET 'localhost:9200/my_index/_search?pretty' -H 'Content-Type: application/json' -d' { "size": 0, "aggs": { "price_ranges": { "range": { "field": "price", "ranges": [ { "to": 100 }, { "from": 100, "to": 200 }, { "from": 200 } ] } } } }'
四、更新和刪除
您可以使用以下命令更新文檔:
curl -XPOST 'localhost:9200/my_index/_update/1?pretty' -H 'Content-Type: application/json' -d' { "doc" : { "content": "This is my second Elasticsearch document." } }'
您可以使用以下命令刪除文檔:
curl -XDELETE 'localhost:9200/my_index/_doc/1?pretty'
五、總結
Elasticsearch是一個適用於各種應用程序的靈活、可擴展和開源的搜索引擎。它提供了許多高級功能,如搜索、聚合和過濾。在這篇文章中,我們講解了如何使用API進行索引、搜索、聚合和過濾,以及如何更新和刪除文檔。希望這篇文章能夠為您提供一個良好的入門指南,讓您更好地了解Elasticsearch的功能。
原創文章,作者:RRXIV,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/361800.html