一、基础语法篇
1、查看全部的索引
GET _cat/indices?v
2、创建students索引库
PUT /students
{
"mappings": {
"properties": {
"title": {
"type": "text",
"index": true,
"store": true,
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
},
"stu_name": {
"type": "keyword",
"index": true,
"store": true
},
"stu_age": {
"type": "integer",
"index": true,
"store": true
},
"sex": {
"type": "text",
"index": true,
"store": true
}
}
}
}
3、添加一条数据
PUT /students/_doc/1
4、查找索引库内id为1的数据
GET /students/_doc/1
5、修改索引库内id为1的数据
PUT /students/_doc/1
验证:查看修改后的内容(GET /students/_doc/1)
6、删除索引库内id为1的数据
DELETE /students/_doc/1
验证:查看修改后的内容(GET /students/_doc/1)
二、进阶语法篇
1、批量添加数据
POST /_bulk
{"create":{"_index":"students" ,"_id":"1"}}
{"stu_name":"李四","stu_age":18,"sex":"女"}
{"create":{"_index":"students" ,"_id":"2"}}
{"stu_name":"张三","stu_age":20,"sex":"男"}
{"create":{"_index":"students" ,"_id":"3"}}
{"stu_name":"王五","stu_age":22,"sex":"男"}
2、根据条件查询数据
1)查询索引内的全部数据
POST /students/_search
{
"query": {
"match_all": {}
}
}
2)根据分词结构进行查询
POST /students/_search
{
"query": {
"match": {
"sex": "女"
}
}
}
3)根据前缀进行查询
POST /students/_search
{
"query": {
"prefix": {
"stu_name": "张"
}
}
}
3、查看ES是如何进行分词的
1)ik_smart分词器
GET /_analyze
{
"analyzer": "ik_smart",
"text": "张三"
}
2)ik_max_word分词器
GET /_analyze
{
"analyzer": "ik_max_word",
"text": "张三"
}
3)默认的分词器standard(一般用来在英文时分词使用)
POST _analyze
{
"analyzer": "standard",
"text": "张三"
}
4、关键字“不分词”精准匹配查找
1)新增一条数据
POST /students/_doc/4
{"stu_name":"张三三","stu_age":22,"sex":"男"}
2)查看“张三三”和“张三的分词情况”
# 张三三的分词情况
GET /_analyze
{
"analyzer": "ik_max_word",
"text": "张三三"
}
# 张三的分词情况
GET /_analyze
{
"analyzer": "ik_max_word",
"text": "张三"
}
3)精准匹配查找
POST /students/_search
{
"query": {
"term": {
"stu_name": {
"value": "张三三"
}
}
}
}
4)多个词精准匹配查找
POST /students/_search
{
"query": {
"terms": {
"stu_name": [
"张三",
"李四"
]
}
}
}
5、指定返回的字段(类似于select xxx from 表…….xxx就是咱们指定返回的字段)
POST /students/_search
{
"query": {
"match_all": {}
}
, "_source": "stu_name"
}
6、取值范围查找
POST /students/_search
{
"query": {
"range": {
"stu_age": {
"gte": 10,
"lte": 20
}
}
}
}
三、升阶语法篇
1、条件组合查询
1)&&的条件组合查询
POST /students/_search
{
"query": {
"bool": {
"must": [
{
"match": {
"stu_name": "张三"
}
},
{
"match": {
"stu_age": 20
}
}
]
}
}
}
2)|| 的条件组合查询
POST /students/_search
{
"query": {
"bool": {
"should": [
{
"match": {
"stu_name": "张三"
}
},
{
"match": {
"stu_age": 22
}
}
]
}
}
}
3)! 取反的条件组合查询
POST /students/_search
{
"query": {
"bool": {
"must_not": [
{
"match": {
"stu_name": "张三"
}
},
{
"match": {
"stu_age": 22
}
}
]
}
}
}
2、聚合函数查询
POST /students/_search
{
"query": {
"match_all": {}
}
, "aggs": {
"age_sum": {
"sum": {
"field": "stu_age"
}
}
}
}
3、排序查询
POST /students/_search
{
"query": {
"match_all": {}
}
, "sort": [
{
"stu_age": {
"order": "desc"
}
}
]
}