一、Restful 风格说明
一种软件架构风格,而不是标准,只是提供了一组设计原则和约束条件。它主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。 基本Rest命令说明:
method | url地址 | 描述 |
---|---|---|
PUT | localhost:9200/索引名称/类型名称/文档id | 创建文档(指定id) |
POST | localhost:9200/索引名称/类型名称 | 创建文档(随机id) |
POST | localhost:9200/索引名称/类型名称/文档id/_update | 修改文档 |
DELETE | localhost:9200/索引名称/类型名称/文档id | 删除文档 |
GET | localhost:9200/索引名称/类型名称/文档id | 通过文档id查询文档 |
POST | localhost:9200/索引名称/类型名称/_search | 查询索引、类型下的所有文档 |
二、基础操作
2.1、指定字段类型创建index
2.1.1、字段类型
- 字符串类型
- text
- keyword
- 数值类型
- long
- integer
- short
- byte
- double
- float
- half_float
- scaled_float
- 日期类型
- date
- 布尔值类型
- boolean
- 二进制类型
- binary
2.1.2、指定字段类型创建索引
语法:
PUT /索引名称
{
"mappings":{
"properties"{
"fieldName":{
"type": ""
}
}
}
}
示例:
PUT /tindex
{
"mappings": {
"properties": {
"name":{
"type": "text"
},
"age":{
"type": "integer"
},
"sex":{
"type": "text"
},
"tags":{
"type": "text"
}
}
}
}
查看index具体信息:
注意:
- es7.x版本,一个index仅仅支持一个type (ex8.x版本以后会废除type的概念),因此通过上述方式创建的index,会有一个默认的type: _doc
通过上述方式创建的index,在 PUT 数据时,需要指定type为_doc,否则会报错:
{
"error" : {
"root_cause" : [
{
"type" : "illegal_argument_exception",
"reason" : "Rejecting mapping update to [tindex] as the final mapping would have more than 1 type: [_doc, user]"
}
],
"type" : "illegal_argument_exception",
"reason" : "Rejecting mapping update to [tindex] as the final mapping would have more than 1 type: [_doc, user]"
},
"status" : 400
}
- 如果未指定类型,es会配置默认字段类型
2.2、添加数据
# 添加数据
PUT /tindex/_doc/1
{
"name": "wells",
"age": 18,
"sex": "man",
"tags": [
"技术宅",
"足球",
"直男"
]
}
PUT /tindex/_doc/2
{
"name": "wells学es",
"age": 20,
"sex": "man",
"tags": [
"宅男",
"乒乓boy",
"唱歌"
]
}
PUT /tindex/_doc/3
{
"name": "jerry",
"age": 40,
"sex": "woman",
"tags": [
"女强人",
"唱歌",
"看书"
]
}
PUT /tindex/_doc/4
{
"name": "tom",
"age": 2,
"sex": "man",
"tags": [
"sqlboy",
"篮球",
"吃货"
]
}
通过 elasticsearch-head 查看当前index结果:
2.3、获取数据
# 获取数据
GET /tindex/_doc/1
2.4、更新数据
推荐使用POST _update方式,原因是:PUT如果不传递值会被覆盖
2.4.1、PUT
# PUT更新数据
PUT /tindex/_doc/1
{
"name": "wells_rename"
}
2.4.2、POST
# POST 更新数据
POST /tindex/_doc/1/_update
{
"doc": {
"age": 17
}
}
2.5、简单条件查询
GET /tindex/_doc/_search?q=name:wells
参考
ES基本操作一 :如何创建、修改、删除索引;批量创建索引;打开、关闭索引;冻结、解冻索引