版本 7.8
1.添加单个文档索引:
curl -X PUT "localhost:9200/customer/_doc/1?pretty" -H 'Content-Type: application/json' -d' {"name": "John Doe"}
如果es中没有此文档
result
是created
,如果存在则是updated
2.查询单个文档
curl -X GET "localhost:9200/customer/_doc/1?pretty"
3.批量索引文件
官方文档提供了测试数据,下载accounts.json
样本数据集,
执行以下命令把数据批量索引
curl -H "Content-Type: application/json" -XPOST "localhost:9200/bank/_bulk?pretty&refresh" --data-binary "@accounts.json"
curl "localhost:9200/_cat/indices?v"
4.查询刚刚录入的数据
curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": { "match_all": {} },
"sort": [
{ "account_number": "asc" }
]
}
'
- took – Elasticsearch运行查询所需的时间(以毫秒为单位)
- timed_out –搜索请求是否超时
- _shards –搜索了多少个分片,以及成功,失败或跳过了多少个分片。
- max_score –找到的最相关文件的分数
- hits.total.value -找到了多少个匹配的文档
- hits.sort -文档的排序位置(不按相关性得分排序时)
- hits._score-文档的相关性得分(使用时不适用match_all)
在请求中加入from
和 size
参数为偏移量和查询条数
这样查询时即从第10条开始查到第19条 共查询10条
curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": { "match_all": {} },
"sort": [
{ "account_number": "asc" }
],
"from": 10,
"size": 10
}
'
要在字段中搜索特定术语,可以使用match查询。例如,以下请求搜索该address字段以查找地址包含mill或的客户lane
curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": { "match": { "address": "mill lane" } }
}
'
要执行词组搜索而不是匹配单个词,请使用 match_phrase代替match。例如,以下请求仅匹配包含短语的地址mill lane:
curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": { "match_phrase": { "address": "mill lane" } }
}
'
搜索40岁的客户但不包括居住在爱达荷州(ID)的任何人:
使用bool参数区分
其中must_not
子句被视为过滤器,不影响评分方式.
curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"bool": {
"must": [
{ "match": { "age": "40" } }
],
"must_not": [
{ "match": { "state": "ID" } }
]
}
}
}
'
范围过滤查询:
例如,以下请求使用范围过滤器将结果限制为余额在20,000美元到30,000美元(含)之间的帐户
curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"bool": {
"must": { "match_all": {} },
"filter": {
"range": {
"balance": {
"gte": 20000,
"lte": 30000
}
}
}
}
}
}
'
5.分组统计聚合查询
curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"size": 0,
"aggs": {
"group_by_state": {
"terms": {
"field": "state.keyword"
}
}
}
}
'
size
设置为0,因此响应仅包含聚合结果.buckets
响应中的是的值state字段中。该 doc_count
节目在每个州帐户数量
curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"size": 0,
"aggs": {
"group_by_state": {
"terms": {
"field": "state.keyword"
},
"aggs": {
"average_balance": {
"avg": {
"field": "balance"
}
}
}
}
}
}
'
指定terms聚合内的顺序来使用嵌套聚合的结果进行排序
curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"size": 0,
"aggs": {
"group_by_state": {
"terms": {
"field": "state.keyword",
"order": {
"average_balance": "desc"
}
},
"aggs": {
"average_balance": {
"avg": {
"field": "balance"
}
}
}
}
}
}
'