【Elasticsearch實踐】(五)ES搜索

一、Restful 風格說明

一種軟件架構風格,而不是標準,只是提供了一組設計原則和約束條件。它主要用於客戶端和服務器交互類的軟件。基於這個風格設計的軟件可以更簡潔,更有層次,更易於實現緩存等機制。 基本Rest命令說明:

method url地址 描述
PUT localhost:9200/索引名稱/類型名稱/文檔id 創建文檔(指定id)
POST localhost:9200/索引名稱/類型名稱 創建文檔(隨機id)
POST localhost:9200/索引名稱/類型名稱/文檔id/_update 修改文檔
DELETE localhost:9200/索引名稱/類型名稱/文檔id 刪除文檔
GET localhost:9200/索引名稱/類型名稱/文檔id 通過文檔id查詢文檔
POST localhost:9200/索引名稱/類型名稱/_search 查詢索引、類型下的所有文檔

二、基礎操作

2.1、指定字段類型創建index

2.1.1、字段類型

  • 字符串類型
    • text
    • keyword
  • 數值類型
    • long
    • integer
    • short
    • byte
    • double
    • float
    • half_float
    • scaled_float
  • 日期類型
    • date
  • 布爾值類型
    • boolean
  • 二進制類型
    • binary

2.1.2、指定字段類型創建索引

語法:

PUT /索引名稱
{
	"mappings":{
		"properties"{
			"fieldName":{
				"type": ""
			}
		}
	}
}

示例:

PUT /tindex
{
  "mappings": {
    "properties": {
      "name":{
        "type": "text"
      },
      "age":{
        "type": "integer"
      },
      "sex":{
        "type": "text"
      },
      "tags":{
        "type": "text"
      }
    }
  }
}

在這裏插入圖片描述
查看index具體信息:
在這裏插入圖片描述
注意:

  • es7.x版本,一個index僅僅支持一個type (ex8.x版本以後會廢除type的概念),因此通過上述方式創建的index,會有一個默認的type: _doc
通過上述方式創建的index,在 PUT 數據時,需要指定type爲_doc,否則會報錯:

{
  "error" : {
    "root_cause" : [
      {
        "type" : "illegal_argument_exception",
        "reason" : "Rejecting mapping update to [tindex] as the final mapping would have more than 1 type: [_doc, user]"
      }
    ],
    "type" : "illegal_argument_exception",
    "reason" : "Rejecting mapping update to [tindex] as the final mapping would have more than 1 type: [_doc, user]"
  },
  "status" : 400
}
  • 如果未指定類型,es會配置默認字段類型

2.2、添加數據

# 添加數據
PUT /tindex/_doc/1
{
  "name": "wells",
  "age": 18,
  "sex": "man",
  "tags": [
    "技術宅",
    "足球",
    "直男"
  ]
}


PUT /tindex/_doc/2
{
  "name": "wells學es",
  "age": 20,
  "sex": "man",
  "tags": [
    "宅男",
    "乒乓boy",
    "唱歌"
  ]
}

PUT /tindex/_doc/3
{
  "name": "jerry",
  "age": 40,
  "sex": "woman",
  "tags": [
    "女強人",
    "唱歌",
    "看書"
  ]
}

PUT /tindex/_doc/4
{
  "name": "tom",
  "age": 2,
  "sex": "man",
  "tags": [
    "sqlboy",
    "籃球",
    "喫貨"
  ]
}

通過 elasticsearch-head 查看當前index結果:
在這裏插入圖片描述

2.3、獲取數據

# 獲取數據
GET /tindex/_doc/1

在這裏插入圖片描述

2.4、更新數據

推薦使用POST _update方式,原因是:PUT如果不傳遞值會被覆蓋

2.4.1、PUT

# PUT更新數據
PUT /tindex/_doc/1
{
  "name": "wells_rename"
}

在這裏插入圖片描述

2.4.2、POST

# POST 更新數據
POST /tindex/_doc/1/_update
{
  "doc": {
    "age": 17
  }
}

在這裏插入圖片描述

2.5、簡單條件查詢

GET /tindex/_doc/_search?q=name:wells

在這裏插入圖片描述

參考

ES基本操作一 :如何創建、修改、刪除索引;批量創建索引;打開、關閉索引;凍結、解凍索引

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章