索引和檢索文件
Elasticsearch 通過 HTTP REST API 訪問,通常使用 cURL 庫。搜尋伺服器和客戶端(你或你的應用程式)之間的訊息以 JSON 字串的形式傳送。預設情況下,Elasticsearch 在埠 9200 上執行。
在下面的示例中,新增了 ?pretty
以告訴 Elasticsearch 美化 JSON 響應。在應用程式中使用這些端點時,無需新增此查詢引數。
索引文件
如果我們打算稍後更新索引中的資訊,最好為我們索引的文件分配唯一的 ID。要將文件新增到名為 megacorp
的索引中,使用型別 employee
和 ID 1
執行:
curl -XPUT "http://localhost:9200/megacorp/employee/1?pretty" -d'
{
"first_name" : "John",
"last_name" : "Smith",
"age" : 25,
"about" : "I love to go rock climbing",
"interests": [ "sports", "music" ]
}'
響應:
{
"_index": "megacorp",
"_type": "employee",
"_id": "1",
"_version": 1,
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"created": true
}
如果在傳送 PUT 呼叫時它不存在,則建立索引。
沒有 ID 的索引
POST /megacorp/employee?pretty
{
"first_name" : "Jane",
"last_name" : "Smith",
"age" : 32,
"about" : "I like to collect rock albums",
"interests": [ "music" ]
}
響應:
{
"_index": "megacorp",
"_type": "employee",
"_id": "AVYg2mBJYy9ijdngfeGa",
"_version": 1,
"_shards": {
"total": 2,
"successful": 2,
"failed": 0
},
"created": true
}
檢索檔案
curl -XGET "http://localhost:9200/megacorp/employee/1?pretty"
響應:
{
"_index": "megacorp",
"_type": "employee",
"_id": "1",
"_version": 1,
"found": true,
"_source": {
"first_name": "John",
"last_name": "Smith",
"age": 25,
"about": "I love to go rock climbing",
"interests": [
"sports",
"music"
]
}
}
從 employee
中獲取 megacorp
索引中的 10 個文件:
curl -XGET "http://localhost:9200/megacorp/employee/_search?pretty"
響應:
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 2,
"max_score": 1,
"hits": [
{
"_index": "megacorp",
"_type": "employee",
"_id": "1",
"_score": 1,
"_source": {
"first_name": "John",
"last_name": "Smith",
"age": 25,
"about": "I love to go rock climbing",
"interests": [
"sports",
"music"
]
}
},
{
"_index": "megacorp",
"_type": "employee",
"_id": "AVYg2mBJYy9ijdngfeGa",
"_score": 1,
"_source": {
"first_name": "Jane",
"last_name": "Smith",
"age": 32,
"about": "I like to collect rock albums",
"interests": [
"music"
]
}
}
]
}
}
使用 match
查詢進行簡單搜尋,該查詢在提供的欄位中查詢完全匹配:
curl -XGET "http://localhost:9200/megacorp/employee/_search" -d'
{
"query" : {
"match" : {
"last_name" : "Smith"
}
}
}'
響應:
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 0.6931472,
"hits": [
{
"_index": "megacorp",
"_type": "employee",
"_id": "1",
"_score": 0.6931472,
"_source": {
"first_name": "John",
"last_name": "Smith",
"age": 25,
"about": "I love to go rock climbing",
"interests": [
"sports",
"music"
]
}
}
]
}
}