執行環境在kibana中
索引的操作
建立索引庫
文法
PUT /索引名稱 {
"settings": {
"屬性名": "屬性值"
}
}
settings:索引庫設定,可以定義索引庫的屬性 比如分片數 副本數等,這裡先不設定
判斷索引是否存在
HEAD /索引名稱
檢視索引
單個索引
GET /索引名稱
批量檢視
GET /索引名稱1,索引名稱2
檢視全部索引1
GET _all
檢視全部索引2
GET /_cat/indices?v
green:索引的所有分片都正常配置設定。
yellow:至少有一個副本沒有得到正确的配置設定。
red:至少有一個主分片沒有得到正确的配置設定。
打開和關閉索引
POST /索引名稱/_open
POST /索引名稱/_close
關閉之後就不能查詢了
删除索引
DELETE /索引名稱1,索引名稱2,索引名稱3...
映射操作
Elasticsearch7.x取消了索引type類型的設定,不允許指定類型,預設為_doc,但字段仍然是有的,我們需要設定字段的限制資訊,叫做字段映射 (mapping)。
建立映射字段
PUT /索引庫名/_mapping
{
"properties": {
"字段名": {
"type": "類型",
"index": true,
"store": true,
"analyzer": "分詞器"
}
}
}
字段名自己定義
屬性包括:
type:類型,可以是text、long、short、date、integer、object等
index:是否索引,預設為true
store:是否存儲,預設為false
analyzer:指定分詞器
等等
官網檢視:https://www.elastic.co/guide/en/elasticsearch/reference/7.3/mapping-params.html
示例:向worker_index設定字段映射
PUT /worker_index/_mapping/
{
"properties": {
"name": {
"type": "text",
"analyzer": "ik_max_word"
},
"job": {
"type": "text",
"analyzer": "ik_max_word"
}
}
}
檢視映射字段
GET /索引名稱/_mapping
檢視所有索引映射關系
GET _mapping
GET _all/_mapping
修改映射關系
修改映射隻能增加字段,做其它更改隻能删除索引 重建立立映射
PUT /索引庫名/_mapping
{
"properties": {
"字段名": {
"type": "類型",
"index": true,
"store": true,
"analyzer": "分詞器"
}
}
}
索引和映射一起建立
put /索引庫名稱
{
"settings":{
"索引庫屬性名":"索引庫屬性值"
},
"mappings":{
"properties":{
"字段名":{
"映射屬性名":"映射屬性值"
}
}
}
}
文檔的操作
新增文檔
指定id的新增文檔
POST /索引名稱/_doc/{id}
{
"field":"value"
}
不指定id的新增文檔
POST /索引名稱/_doc
{
"field":"value"
}
檢視單個文檔
GET /索引名稱/_doc/{id}
檢視所有文檔
POST /索引名稱/_search
{
"query": {
"match_all": {}
}
}
_source定制傳回結果
讓source隻傳回需要的結果
GET /worker_index/_doc/1?_source=name
更新文檔
全部更新
隻保留更新的字段,沒有的字段就被删除了
PUT /索引名稱/_doc/{id}
{
"field":"value"
}
把剛才新增的請求方式POST改為PUT,就是修改了,不過修改必須指定id,id對應文檔存在,則修改, id對應文檔不存在,則新增
檢視一下,可以看到之前的job字段已經沒有了
局部更新
隻是修改某個字段
POST /索引名/_update/{id}
{
"doc":{
"field":"value"
}
}
檢視一下,可以看到之前的字段還在
帶樂觀鎖的更新
建立文檔
PUT /test_index/_doc/4
{
"test_field": "test"
}
擷取資料
GET /test_index/_doc/4
#傳回
{
"_index" : "test_index",
"_type" : "_doc",
"_id" : "4",
"_version" : 1,
"_seq_no" : 0,
"_primary_term" : 1,
"found" : true,
"_source" : {
"test_field" : "test"
}
}
更新
- 使用if_seq_no和 if_primary_term進行樂觀鎖控制
PUT /test_index/_doc/4?if_seq_no=0&if_primary_term=1
{
"test_field": "changed"
}
-
external version進行樂觀鎖并發控制
這裡version=2的版本号,要比上面get拿到的version的版本号大才能更新
PUT /test_index/_doc/4?version=2&version_type=external
{
"test_field": "changed"
}
删除文檔
根據id删除
DELETE /索引名/_doc/{id}
根據查詢條件删除
POST /索引庫名/_delete_by_query
{
"query": {
"match": {
"字段名": "搜尋關鍵字"
}
}
}
示例
POST /lagou-company-index/_delete_by_query
{
"query":{
"match":{
"name":"Jack"
}
}
}
删除所有文檔
POST 索引名/_delete_by_query
{
"query": {
"match_all": {}
}
}