基于Elasticsearch 快速开始 | 易学教程 (e-learn.cn)学习总结,详细请自行移步
熟悉以下命令:
索引:
1、创建一个索引,索引名为test_index_1
curl -X PUT "localhost:9200/test_index_1?pretty"
2、删除一个名为test_index_1的索引
curl -X DELETE "localhost:9200/test_index_1?pretty"
3、查询所有索引
curl -X GET "localhost:9200/_cat/indices?v"
数据更改:
1、添加一个数据(文档)到索引test_index_1
curl -X PUT "localhost:9200/test_index_1/_doc/1?pretty" -H 'Content-Type: application/json' -d'{"name": "John Doe"}'
以上是将数据{"name": "John Doe"}添加到了索引test_index_1,并指定了文档的内部id为1(_doc后的路径就是id)
备注:Elasticsearch并不要求在索引文档之前就先创建索引,然后才能将文档编入索引。在前面的示例中,如果事先不存在"test_index_1"索引,Elasticsearch将自动创建"test_index_1"索引
2、更新数据(文档)
Elasticsearch更新数据都是先删除后新增
curl -X POST "localhost:9200/test_index_1/_doc/1/_update?pretty" -H 'Content-Type: application/json' -d' { "doc": { "name": "Jane Doe", "age": 20 } } '
这里是更改了id为1的数据,即更改了name字段的数据并增加了一个age字段的数据
更新数据-另一种方式
curl -X POST "localhost:9200/test_index_1/_doc/1/_update?pretty" -H 'Content-Type: application/json' -d' { "script" : "ctx._source.age += 5" } '
这里将age字段的数据增加5,ctx._source的意思是引用的当前源文档
3、删除数据(文档)
curl -X DELETE "localhost:9200/test_index_1/_doc/2?pretty"
从"test_index_1"索引中删除ID为2的文档
4、批处理
Elasticsearch还可以使用_bulk API批量执行上述任何操作
curl -X POST "localhost:9200/test_index_1/_doc/_bulk?pretty" -H 'Content-Type: application/json' -d $' {"index":{"_id":"3"}}\n{"name": "John Doe" }\n{"index":{"_id":"4"}}\n{"name": "Jane Doe" }\n'
同时添加了id为3和4的文档
备注:这里使用了$''的方式使\n能被解析,因为批量的格式是一个数据单独一行,
通过传json文件方式的批处理,新建一个json格式文件test.json,里面数据如下图:
执行命令:curl -H "Content-Type: application/json" -XPOST 'localhost:9200/test_index_1/_bulk?pretty' --data-binary "@test.json"
数据查询
简单的2种搜索,一种是通过REST请求URI发送检索参数,另一种是通过REST请求体发送检索参数。(一种是把检索参数放在URL后面,另一种是放在请求体里面。相当于HTTP的GET和POST请求)
第一种: curl -X GET "localhost:9200/test_index_1/_search?q=*&sort=account_number:asc&pretty"
q=* 表示匹配所有文档
sort=account_number:asc 表示按每个文档的account_number字段升序排序
pretty 表示返回漂亮打印的JSON结果......
下面是请求体的写法
第二种: curl -X GET "localhost:9200/test_index_1/_search" -H 'Content-Type: application/json' -d' { "query": { "match_all": {} }, "sort": [ { "account_number": "asc" } ] } '