基于HTTP協議,以JSON為數據交互格式的RESTful API
其他所有程序語言都可以使用RESTful API,通過9200端口的與Elasticsearch進行通信,你可以使用你喜歡的WEB客戶端,事實上,如你所見,你甚至可以通過curl
命令與Elasticsearch通信。
curl -X<VERB> '<PROTOCOL>://<HOST>:<PORT>/<PATH>?<QUERY_STRING>' -d '<BODY>'
- VERB HTTP方法:
GET
,POST
,PUT
,HEAD
,DELETE
- PROTOCOL http或者https協議(只有在Elasticsearch前面有https代理的時候可用)
- HOST Elasticsearch集群中的任何一個節點的主機名,如果是在本地的節點,那么就叫localhost
- PORT Elasticsearch HTTP服務所在的端口,默認為9200
- PATH API路徑(例如_count將返回集群中文檔的數量),PATH可以包含多個組件,例如_cluster/stats或者_nodes/stats/jvm
- QUERY_STRING一些可選的查詢請求參數,例如
?pretty
參數將使請求返回更加美觀易讀的JSON數據 - BODY 一個JSON格式的請求主體(如果請求需要的話)
面向文檔
Elasticsearch是面向文檔(document oriented)的,這意味著它可以存儲整個對象或文檔(document)。然而它不僅僅是存儲,還會索引(index)每個文檔的內容使之可以被搜索。在Elasticsearch中,你可以對文檔(而非成行成列的數據)進行索引、搜索、排序、過濾。這種理解數據的方式與以往完全不同,這也是Elasticsearch能夠執行復雜的全文搜索的原因之一。
JSON
ELasticsearch使用Javascript對象符號(JavaScript Object Notation),也就是JSON,作為文檔序列化格式。JSON現在已經被大多語言所支持,而且已經成為NoSQL領域的標準格式。它簡潔、簡單且容易閱讀。
概念對比
關系型數據庫 | ElasticSearch | 備注說明 Relational DB / ES |
---|---|---|
Databases | Indices(Indexes) | 數據庫/索引 |
Tables | Types | 表 / 類型 |
Rows | Documents | 記錄 / 文檔 |
Columns | Fields | 列 / 字段 |
測試
PUT /megacorp/employee/1
{
"first_name" : "John",
"last_name" : "Smith",
"age" : 25,
"about" : "I love to go rock climbing",
"interests": [ "sports", "music" ]
}
我們看到path: /megacorp/employee/1
包含三部分信息:
名字 | 說明 |
---|---|
megacorp | 索引名 |
employee | 類型名 |
1 | 這個員工的ID |
在ES中PUT和POST都會覆蓋原來的數據,沒有就會更新
檢索文檔
http://localhost:9200/megacorp/employee/1
結果
{
"_index": "megacorp",
"_type": "employee",
"_id": "1",
"_version": 1,
"_seq_no": 0,
"_primary_term": 1,
"found": true,
"_source": {
"first_name": "John",
"last_name": "Smith",
"age": 25,
"about": "I love to go rock climbing",
"interests": [
"sports",
"music"
]
}
}
檢索所有員工
http://localhost:9200/megacorp/employee/_search
這個會返回所有員工的信息,默認展示20條文檔
加入檢索條件
http://localhost:9200/megacorp/employee/_search?q=first_name:sheng
返回結果
{
"took": 5,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 0.6931472,
"hits": [
{
"_index": "megacorp",
"_type": "employee",
"_id": "4",
"_score": 0.6931472,
"_source": {
"first_name": "sheng",
"last_name": "yulong",
"age": 28,
"about": "This is for everyone!",
"interests": [
"music"
]
}
}
]
}
}
查詢字符串 傳遞給參數q,值和查詢字符串用
:
隔開
那么如果有更加復雜的搜索呢,怎么操作呢?我們下回分解。