Elasticsearch 基本数据操作

创建索引

1
curl -X PUT localhost:9200/accounts/person

插入或更新

插入或更新主要使用POST与PUT,POST可以不加id参数,会自动生成一随机id,而PUT必须指定id才能执行,两个方式都可以指定id。

单独插入或修改

POST:

1
2
3
curl -X POST -H 'Content-Type:application/json' localhost:9200/accounts/person/1 -d '
{"ages":99,"name":"sllin"}
'

PUT:

1
2
3
curl -X PUT -H 'Content-Type:application/json' localhost:9200/accounts/person/1 -d '
{"ages":99,"name":"sllin"}
'

POST或PUT都不能直接手动往上传数据中加_id值:

1
2
3
curl -X POST -H 'Content-Type:application/json' localhost:9200/accounts/person -d '
{"ages":20,"_id":1}
'

会得到错误"Field [_id] is a metadata field and cannot be added inside a document"

更新与插入是同种操作方式,都使用POST或PUT,都会直接覆盖掉原来的数据。

批量插入

使用_bulk,两行数据构成一次操作,插入的数据作为后面测试查询使用:

1
2
3
4
5
6
7
8
9
10
curl -H "Content-Type: application/json" -X POST localhost:9200/accounts/person/_bulk -d '
{"index":{"_id":1}}
{"name":"Sllin","age":88,"birthday":"1920-09-09"}
{"index":{"_id":2}}
{"name":"Lin","age":99,"birthday":"1910-02-02"}
{"index":{"_id":3}}
{"name":"Jim","age":77,"birthday":"1930-01-01"}
{"index":{"_id":4}}
{"name":"Dalin","age":78,"birthday":"1931-01-01"}
'

查询

普通查询

单字段匹配查询,查询namesllin的文档

1
2
3
4
curl -H "Content-Type:Application/json" -X GET localhost:9200/accounts/person/_search -d '
{
"query":{"match":{"name":"Sllin"}}
}'

OR查询,查询nameSllinLin的文档

1
2
3
4
curl -H "Content-Type:Application/json" -X GET localhost:9200/accounts/person/_search -d '
{
"query":{"match":{"name":"Sllin Lin"}}
}'

布尔查询

bool必须为真时才会匹配,must相当于AND, must_not相当于NOTshould相当于OR
查询namesllinage为88的文档

1
2
3
4
5
6
7
curl -H "Content-Type:Application/json" -X GET localhost:9200/accounts/person/_search -d '{
"query":{
"bool":{
"should":[{"match":{"name":"Sllin"}}, {"match":{"age":99}}]
}
}
}'

查询namesllin同时age88的文档

1
2
3
4
5
6
7
curl -H "Content-Type:Application/json" -X GET localhost:9200/accounts/person/_search -d '{
"query":{
"bool":{
"must":[{"match":{"name":"Sllin"}}, {"match":{"age":88}}]
}
}
}'

查询name不为sllinage不为99的文档

1
2
3
4
5
6
7
curl -H "Content-Type:Application/json" -X GET localhost:9200/accounts/person/_search -d '{
"query":{
"bool":{
"must_not":[{"match":{"name":"Sllin"}}, {"match":{"age":99}}]
}
}
}'

范围查询

可以根据数值,日期的范围取值
主要有取值参数:

1
2
3
4
gt: 大于
gte:大于或等于
lt: 小于
lte:小于或等于

查询生日大于1930-01-01的文档

1
2
3
4
5
6
curl -H "Content-Type:Application/json" -X GET localhost:9200/accounts/person/_search -d '
{
"query":{
"range":{"birthday":{"gte":"1930-01-01"}}
}
}'

查询生日等于1930-01-01的文档,因为没有等于参数,所以同时使用gtelte

1
2
3
4
5
6
curl -H "Content-Type:Application/json" -X GET localhost:9200/accounts/person/_search -d '
{
"query":{
"range":{"birthday":{"gte":"1930-01-01","lte":"1930-01-01"}}
}
}'

删除

根据查询删除:

1
2
3
4
5
curl -H "Content-Type:Application/json" -X POST localhost:9200/accounts/person/_delete_by_query -d '
{
"query":
{"match":{"name":"Dalin"}}
}'

删除索引:

1
curl -X DELETE localhost:9200/accounts

通配符删除索引:

1
curl -X DELETE localhost:9200/accounts_*

- - END - -


腾讯云
0%