记录一下,elasticsearch从创建索引到插入数据的一个crud操作。
一、创建索引
curl -XPUT "http://192.168.99.1:9200/productindex" -d' { "settings": { "number_of_shards": 1, "number_of_replicas": 1 }, "mappings": { "product" : { "properties": { "name" : { "type": "text", "fielddata": true }, "price" : { "type": "long" } } } } }'
二、插入数据
1、如果需要插入的数据已经存在,那么执行替换操作,如果不存在则执行插入操作
注意: 1、此处是手动指定的id的值
2、如果productindex/product/1 这个数据存在,如果请求体中只有name字段,那么这行数据的price字段就会被删除,即执行的是替换操作,而不是更新操作
curl -XPUT "http://192.168.99.1:9200/productindex/product/1" -d' { "name" : "pen", "price" : 2 }'
2、如果数据已经存在,那么就报错,不存在则执行插入操作
注意:此处只需要加上_create或加上op_type=create即可
curl -XPUT "http://192.168.99.1:9200/productindex/product/1?op_type=create" -d' { "name" : "new pen", "price" : 2 }'
或
curl -XPUT "http://192.168.99.1:9200/productindex/product/1/_create" -d' { "name" : "new pen", "price" : 2 }'
3、插入数据的时候自动生成id的值
注意:此处就需要使用post请求,而不是使用put请求。
curl -XPOST "http://192.168.99.1:9200/productindex/product" -d' { "name" : "pen", "price" : 2 }'
三、修改数据
1、使用_update或op_type=update指定修改,数据不存在报错
curl -XPOST "http://192.168.99.1:9200/productindex/product/1/_update" -d' { "doc": { "name" : "update new name" } }'
2、使用乐观锁version控制修改(防止在并发情况下数据修改有误)
后方的这个version的值为数据当前的版本号,如果es中这个数据的版本号发生了变化,则修改失败。
curl -XPOST "http://192.168.99.1:9200/productindex/product/1/_update?version=7" -d' { "doc": { "name" : "update new name" } }'
3、使用upsert操作,如果数据不存在则执行upsert部分(插入操作),否则执行更新操作
curl -XPOST "http://192.168.99.1:9200/productindex/product/12/_update" -d' { "doc":{ "name":"update new value" }, "upsert" : { "name" : "数据不存在执行插入操作", "price" : 1 } }'
或执行如下操作 (使用doc_as_upsert,如果文档不存在,则将doc的部分当做upsert的部分)
curl -XPOST "http://192.168.99.1:9200/productindex/product/13/_update" -d' { "doc":{ "name":"update new value" }, "doc_as_upsert" : true }'
四、高亮查询
1、插入一条新的数据
curl -XPUT "http://192.168.99.1:9200/productindex/product/29" -d' { "name" : "new name", "desc" : "this is a desc field" }'
2、匹配name字段中有has name的值或desc字段中有desc的值,并对匹配到的值进行高亮
curl -XGET "http://192.168.99.1:9200/productindex/product/_search" -d' { "query": { "bool": { "should": [ { "match": { "name": "has name" } }, { "term": { "desc": { "value": "desc" } } } ] } }, "highlight": { "pre_tags": "<span style=\"color:red\">", "post_tags": "</span>", "fields": { "name" : { "pre_tags": "<span style=\"color:blue\">", "post_tags": "</span>" }, "*" : { } } } }'
五、删除数据
1、删除id=1的数据
curl -XDELETE "http://192.168.99.1:9200/productindex/product/1"