Elasticsearch使用REST API實現全文檢索


Elasticsearch REST API

elasticsearch支持通過http請求響應服務,http請求默認使用9200斷開,因此通過curl命令,可以發送http請求,並得到json返回內容。常用的REST API包括一下幾個:

檢查ES集群狀態

curl http://localhost:9200/_cat/health?v

檢查ES節點的狀態

curl http://localhost:9200/_cat/nodes?v

查詢所有的索引

curl http://localhost:9200/_cat/indices?v

創建索引

curl -XPUT http://localhost:9200/myindex/mytype/id -H 'Content-Type: application/json' -d '{"name":"ysl"}'

刪除索引

curl -XDELETE http://localhost:9200/myindex

查詢索引

curl -XGET http://localhost:9200/myindex/mytype/id

添加數據

curl -XPUT 'http://localhost:9200/kimchy/doc/1?pretty' -H 'Content-Type: application/json' -d '
{
    "user": "kimchy",
    "post_date": "2009-11-15T13:12:00",
    "message": "Trying out Elasticsearch, so far so good?"
}'

查詢數據

curl -XGET 'http://localhost:9200/kimchy,another_user/_search?pretty=true' -H 'Content-Type: application/json' -d '
{
    "query" : {
        "match_all" : {}
    }
}'

批量添加數據

動態映射無法添加數據,不要擔心!可以使用bulk命令,添加json文件內的數據

定義json數據

{"index":{"_index":"test123","_id":1}}
{"name":"ysl","age":25}
{"index":{"_index":"test123","_id":2}}
{"name":"wdd","age":25}
{"index":{"_index":"test123","_id":3}}
{"name":"yjb","age":25}

注意的是,json文件名稱隨意指定,第一行定義了索引和一些常用字段:

  •  _index定義了索引的名稱,如果沒有指定需要在curl命令中添加索引名稱字段
  • _type定義了索引的類型,如果沒有指定需要在curl命令中添加索引類型字段
  •  _id定義了該行數據的id,如果沒有指定,會隨機生成一串數字。

執行命令

進入到json文件所在的目錄,執行一下命令:

curl localhost:9200/索引名稱/索引類型/_bulk?pretty --data-binary @data.json

注意的是:如果json文件中定義了_index和_type,那么這里可以不寫(即便寫了也會按照json文件中的生成)。

curl localhost:9200/_bulk?pretty --data-binary @data.json

類似的,如果按照上面我們定義了_index卻沒有定義_type,那么索引會是test123,類型為我們curl命令中指定的類型。

執行上述命令

 curl http://localhost:9200/test123/test123/_bulk?pretty --data-binary @data.json

得到以下結果

{
  "took" : 1233,
  "errors" : false,
  "items" : [ {
    "index" : {
      "_index" : "test123",
      "_type" : "test123",
      "_id" : "1",
      "_version" : 1,
      "_shards" : {
        "total" : 2,
        "successful" : 1,
        "failed" : 0
      },
      "status" : 201
    }
  }, {
    "index" : {
      "_index" : "test123",
      "_type" : "test123",
      "_id" : "2",
      "_version" : 1,
      "_shards" : {
        "total" : 2,
        "successful" : 1,
        "failed" : 0
      },
      "status" : 201
    }
  } ]
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM