600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > Elasticsearch使用REST API实现全文检索

Elasticsearch使用REST API实现全文检索

时间:2018-08-04 12:17:23

相关推荐

Elasticsearch使用REST API实现全文检索

Elasticsearch REST API

elasticsearch支持通过http请求响应服务,http请求默认使用9200断开,因此通过curl命令,可以发送http请求,并得到json返回内容。常用的REST API包括一下几个:

检查ES集群状态

curl http://localhost:9200/_cat/health?v

检查ES节点的状态

curl http://localhost:9200/_cat/nodes?v

查询所有的索引

curl http://localhost:9200/_cat/indices?v

创建索引

curl -XPUT http://localhost:9200/myindex/mytype/id -H 'Content-Type: application/json' -d '{"name":"ysl"}'

删除索引

curl -XDELETE http://localhost:9200/myindex

查询索引

curl -XGET http://localhost:9200/myindex/mytype/id

添加数据

curl -XPUT 'http://localhost:9200/kimchy/doc/1?pretty' -H 'Content-Type: application/json' -d '{"user": "kimchy","post_date": "-11-15T13:12:00","message": "Trying out Elasticsearch, so far so good?"}'

查询数据

curl -XGET 'http://localhost:9200/kimchy,another_user/_search?pretty=true' -H 'Content-Type: application/json' -d '{"query" : {"match_all" : {}}}'

批量添加数据

动态映射无法添加数据,不要担心!可以使用bulk命令,添加json文件内的数据

定义json数据

{"index":{"_index":"test123","_id":1}}{"name":"ysl","age":25}{"index":{"_index":"test123","_id":2}}{"name":"wdd","age":25}{"index":{"_index":"test123","_id":3}}{"name":"yjb","age":25}

注意的是,json文件名称随意指定,第一行定义了索引和一些常用字段:

_index定义了索引的名称,如果没有指定需要在curl命令中添加索引名称字段_type定义了索引的类型,如果没有指定需要在curl命令中添加索引类型字段_id定义了该行数据的id,如果没有指定,会随机生成一串数字。

执行命令

进入到json文件所在的目录,执行一下命令:

curl localhost:9200/索引名称/索引类型/_bulk?pretty --data-binary @data.json

注意的是:如果json文件中定义了_index和_type,那么这里可以不写(即便写了也会按照json文件中的生成)。

curl localhost:9200/_bulk?pretty --data-binary @data.json

类似的,如果按照上面我们定义了_index却没有定义_type,那么索引会是test123,类型为我们curl命令中指定的类型。

执行上述命令

curl http://localhost:9200/test123/test123/_bulk?pretty --data-binary @data.json

得到以下结果

{"took" : 1233,"errors" : false,"items" : [ {"index" : {"_index" : "test123","_type" : "test123","_id" : "1","_version" : 1,"_shards" : {"total" : 2,"successful" : 1,"failed" : 0},"status" : 201}}, {"index" : {"_index" : "test123","_type" : "test123","_id" : "2","_version" : 1,"_shards" : {"total" : 2,"successful" : 1,"failed" : 0},"status" : 201}} ]}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。