一、elasticsearch文档操作是什么?
我们都知道,在数据库里面,有很多的查询语句,插入数据,更新数据,删除数据等等,那么同理,在elasticsearch当中,也有类似的操作,只不过语法跟数据库不同罢了,那么究竟怎么使用呢?下面我们来看下。
二、使用步骤
1.添加数据
#往索引lhh里面加入一条信息
put /lhh/user/1
{
"name":"miracle_gir",
"age":25,
"desc":"一定可以找到适合的工作的!",
"tags":["编程","阅读","跑步","游戏"]
}
get lhh
#运行结果
{
"lhh" : {
"aliases" : {
},
"mappings" : {
"properties" : {
"age" : {
"type" : "long"
},
"desc" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"name" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"tags" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
},
"settings" : {
"index" : {
"creation_date" : "1614345848042",
"number_of_shards" : "1",
"number_of_replicas" : "1",
"uuid" : "3quPlmFTTiGToEZql-BBmA",
"version" : {
"created" : "7060299"
},
"provided_name" : "lhh"
}
}
}
}
2.获取数据
#获取1号用户
get /lhh/user/1
#运行结果
#! Deprecation: [types removal] Specifying types in document get requests is deprecated, use the /{index}/_doc/{id} endpoint instead.
{
"_index" : "lhh",
"_type" : "user",
"_id" : "1",
"_version" : 2,
"_seq_no" : 1,
"_primary_term" : 1,
"found" : true,
"_source" : {
"name" : "miracle_gir",
"age" : 25,
"desc" : "一定可以找到适合的工作的!",
"tags" : [
"编程",
"阅读",
"跑步",
"游戏"
]
}
}
3.更新数据
put /lhh/user/1
{
"name":"lhh_mir_gir",
"age":26,
"desc":"我慢慢爱上写代码了,不知道这是不是真的!"
}
#运行结果
#! Deprecation: [types removal] Specifying types in document index requests is deprecated, use the typeless endpoints instead (/{index}/_doc/{id}, /{index}/_doc, or /{index}/_create/{id}).
{
"_index" : "lhh",
"_type" : "user",
"_id" : "1",
"_version" : 3,
"result" : "updated",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 2,
"_primary_term" : 1
}
但是我们现在不全部填充字段,我们只设置两个字段,那么会发生什么呢?
put /lhh/user/1
{
"name":"lhh_mir_gir",
"age":3
}
#运行结果
#! Deprecation: [types removal] Specifying types in document index requests is deprecated, use the typeless endpoints instead (/{index}/_doc/{id}, /{index}/_doc, or /{index}/_create/{id}).
{
"_index" : "lhh",
"_type" : "user",
"_id" : "1",
"_version" : 4,
"result" : "updated",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 3,
"_primary_term" : 1
}
结论:put /索引/类型/文档id
文档id相同的情况下会覆盖掉之前的数据。
于是还有另外一种更新的操作,那就是post操作。
post /lhh/user/1/_update
{
"doc":{
"name":"abcdef"
}
}
#运行结果
#! Deprecation: [types removal] Specifying types in document update requests is deprecated, use the endpoint /{index}/_update/{id} instead.
{
"_index" : "lhh",
"_type" : "user",
"_id" : "1",
"_version" : 6,
"result" : "updated",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 6,
"_primary_term" : 1
}
4.查询语句
假设我们的lhh索引里面有这些数据。
标题简单查询语句
get lhh/user/_search?q=name:lhh1号
#运行结果,其中的score就代表权重,权重越大,代表查询越精确。
#! Deprecation: [types removal] Specifying types in search requests is deprecated.
{
"took" : 6,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed"