ES 的 RESTFUL API 常用示例

目录

前言

一、创建索引

二、新增或修改记录

三、删除数据

四、查询数据



前言

在这里记录ES的几种简单的 restful api操作,方便使用es开发过程中数据的模拟与验证。

下面示例中用到的index统一为blog,type统一为article。


一、创建索引

创建一个index为blog的索引,索引中的type为articl

#请求类型: PUT
#索引类型: blog

http://IP:9200/blog
 
# type: article
# properties中存储字段信息
{
	 "mappings":{
		 "article":{
			 "properties":{
				 "id":{
					 "type":"long",
					 "store":true,
					 "index":true
				 },
				 "title":{
					 "type":"text",
					 "store":true,
					 "index":true,
					 "analyzer":"standard"
				 },
				 "content":{
					 "type":"text",
					 "store":true,
					 "index":true,
					 "analyzer":"standard"
				 }
			 }
		 }
	 }
 }

如果在创建索引时,未设定mapping信息,可以重新设定。

# 请求类型: POST
# index :blog
# type: article
#_mapping 表示要对mapping进行操作 

POST  http://IP:9200/blog/article/_mapping


{
		 "article":{
			 "properties":{
				 "id":{
					 "type":"long",
					 "store":true,
					 "index":true
				 },
				 "title":{
					 "type":"text",
					 "store":true,
					 "index":true,
					 "analyzer":"standard"
				 },
				 "content":{
					 "type":"text",
					 "store":true,
					 "index":true,
					 "analyzer":"standard"
				 }
			 }
		 }
}

二、新增或修改记录

如果Es中不存在数据则新增,如果存在则修改。

#请求类型 POST
#index: blog
#type: article
# 字符串1 代表主键(_id=1),如果不写由Es自动生成

POST http://localhost:9200/blog/article/1


{
	"id":"1",
	"title":"这是一个标题",
	"content":"这是一段内容"
}

三、删除数据

# 请求类型 DELETE
# index: blog
# type : article
# 文档id :1

DELETE http://IP:9200/blog/article/1

##如果只写请求路径只到索引层级,则代表删除索引,示例:
DELETE http://IP:9200/blog

###如果请求路径到type层级,则代表删除type,示例:
DELETE http://IP:9200/blog/article

四、查询数据

一共有三种查询方式

1. 根据文档主键id进行查询 

GET http://IP:9200/blog/article/1

2. 根据关键词查询 
#_search 代表需要执行查询操作

POST http://localhost:9200/blog/article/_search

{
	"query":{
		"term":{
			"title":"标题"
		}
	}
}


3 分词查询(query_string)
POST http://localhost:9200/blog2/article/_search

{
	"query":{
		"query_string":{
			"default_field":"title",
			"query":"标题内容"
		}
	}
}

 五、通过sql查询数据

POST /_sql?format=txt
{
  "query": "SELECT count(1) FROM index_name where field = 'value' LIMIT 5"
}

# format=txt format 代表返回的结果格式,可以选择 txt 或 json两种格式

# query 的值就是sql语句

六、通过脚本更新es数据

POST  index_name/_doc/_update_by_query

{
  "script": {
    "lang": "painless",
    "inline": "if (ctx._source.field == null) {ctx._source.field = 'value'}"
  },
  "query":{
    "match_all": {}
  }
}

## 通过查询出来的数据更新数据
# query对应于查询语句
# inline 后边是js脚本


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值