ES基于Restful的API
大约 2 分钟
官网地址:https://www.elastic.co/guide/cn/elasticsearch/guide/current/foreword_id.html
------ 服务状态 ------
查询状态
GET /_cat/health
查看分词器分词结果
POST /_analyze
{
"analyzer": "ik_max_word",
"text": "我是一名学生"
}
------ 文档管理 ------
添加索引
settings
分片数
(number_of_shards):早期版本默认是5片,ES7中默认是1片;
副本数
(number_of_replicas):默认是1,每个分片默认都有一个副本。
mappings
:可不指定,会自动创建
PUT /my_index
{
"settings": {
"number_of_shards": 1,
"number_of_replicas": 1
},
"mappings": {
"properties": {
"id": {
"type": "long"
},
"title": {
"type": "text",
"analyzer": "standard",
"store": "true",
"index": true
},
"mobile": {
"type": "keyword",
"store": "true",
"index": true
},
"comment": {
"type": "text",
"analyzer": "standard",
"store": "true",
"index": true
}
}
}
}
添加数据
{ PUT | POST } http://192.168.68.129:9200/{索引}/_doc/{_id}
POST /blog/_doc/1
{
"id":1,
"title":"文章标题",
"content":"这是一篇文章",
"comment":"备注信息",
"mobile":"13344556677"
}
批量添加数据
{ PUT | POST } http://192.168.68.129:9200/{索引}/_bulk
POST /blog/_bulk
{"index":{"_id":1}}
{"id":1, "title":"李宇春发新歌《软肋》,剖析自我成长的道路", "content":"李宇春发新歌《软肋》,剖析自我成长的道路", "comment":"娱乐", "mobile":"13900112239"}
{"index":{"_id":2}}
{"id":2, "title":"《奔跑吧9》4月23日开播,沙溢、蔡徐坤等回归", "content":"《奔跑吧9》4月23日开播,沙溢、蔡徐坤等回归", "comment":"娱乐", "mobile":"13900112233"}
根据_id取文档
删除索引
------ 数据查询 ------
精确查询(term)
字段匹配,考虑字段的分词器,standard针对中文,一个字为一个词。
GET /blog/_search
{
"query": {
"term": {
"title": "java"
}
}
}
组合查询(bool)
must
:必须满足,相当于是AND
should
:应该满足,相当于OR
must_not
:必须不能满足,相当于NOT
filter
:过滤查询结果,不进行打分
GET /blog/_search
{
"query": {
"bool": {
"must": [
{"term": {"title": "跑"}},
{"terms": {"content": ["跑","春"]}}
],
"must_not": [
{"term": {"title": "跑"}},
{"term": {"content": "跑"}}
],
"should": [
{"term": {"title": "跑"}},
{"term": {"content": "跑"}}
],
"filter": [
{"term": {"title": "跑"}},
{"term": {"content": "跑"}}
]
}
}
}
匹配查询(query_string)
在查询之前,可以对查询条件进行分词处理,然后基于分词之后的结果再次查询。
query_string
和match
效果一样。
GET /blog/_search
{
"query": {
"query_string": {
"default_field": "title",
"query": "奔跑跑男"
}
}
}
------------------------------------------
GET /blog/_search
{
"query": {
"match": {
"title": "QUICK!"
}
}
}
多字段查询(multi_match)
指定在多个字段中查询
GET /blog/_search
{
"query": {
"multi_match": {
"query": "跑男",
"fields": ["title","comment"]
}
}
}
高亮显示(highlight)
POST /blog/_search
{
"query": {
"term": {
"title": {
"value": "跑"
}
}
},
"highlight": {
"fields": {
"title": {},
"content": {}
},
"pre_tag": "<em>",
"post_tag": "</em>"
}
}
分页查询
from
:起始的行号,从0开始,size
:每页显示的记录数量
POST /blog/_search
{
"query": {
"term": {
"title": {
"value": "跑"
}
}
},
"from": 10,
"size": 5
}