Elasticsearch类似于一个用来存储文档的数据库。所以学习它的查询语句时我们和mysql的做个对比。
Elasticsearch的索引相当于mysql中的数据库;
Elasticsearch的类型相当于mysql的表明;
Elasticsearch的查询风格类似于restful的风格。
1.添加数据
POST /test/article/1
{
"title":"java学习教程",
"content":"这是一本关于java的书",
"author":"王五",
"age":30
}
test 为索引
article 为类型
1 为ID
如果返回的结果如下说明数据创建成功:
{
"_index" : "test",
"_type" : "article",
"_id" : "1",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 0,
"_primary_term" : 1
}
2.删除数据
DELETE /test/article/1
如果删除的id不存在,则会报not_found的错误
3.修改数据
PUT /test/article/1
{
"title":"java学习教程",
"content":"这是一本关于java的书",
"author":"王五",
"age":31
}
如果已经存在ID为1的数据,则会执行更新操作。如果不存在则执行insert操作。
响应体:
{
"_index" : "test",
"_type" : "article",
"_id" : "1",
"_version" : 2,
"result" : "updated",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 6,
"_primary_term" : 1
}
重点关注version的值变成了2,插入一次更新一次说以变成了2
4.查询
查询全部数据
GET /test/article/_search
{
"query": {
"match_all": {}
}
}
查询全部数据,但是只查询部分字段
GET /test/article/_search
{
"query": {"match_all": {}},
"_source": ["title","content"]
}
分页查询
GET /test/article/_search
{
"query": {
"match_all": {}
},
"from": 0,
"size": 2
}
查询时按照某个字段排序
GET /test/article/_search
{
"query": {
"match_all": {}
},
"sort": [
{
"age": {
"order": "asc"
}
}
]
}
查询title中包含java的数据(这种查询方式会将内容中包含这或者 关于字的所有数据查询出来。同时会将匹配度最高的显示在第一条)。如果想要查询出包含这并且包含关于的数据时。可以使用operator参数。
GET /test/article/_search
{
"query": {
"match": {
"content": "这 关于"
}
}
}
GET /test/article/_search
{
"query": {
"match": {
"content": {
"query": "这 关于",
"operator": "and"
}
}
}
}
同时我们可以使用minimum_should_match来控制匹配的百分比
GET /test/article/_search
{
"query": {
"match": {
"content": {
"query": "这 关 于",
"minimum_should_match": "75%"
}
}
}
}
这里查询的条件为三个。所以会向下取整为66.6%。当满足66.6%的匹配度时就会查询出来
精确查询
先添加一条数据
POST /test/article/5
{
"title":"java",
"content":"这java是编程语言",
"author":"java",
"age":27
}
我们想查询出所有包含这和java 的数据。并且这两个查询条件不能被其他字隔开
GET /test/article/_search
{
"query": {
"match_phrase": {
"content": "这java"
}
}
}
其实这就是match_phrase和match的区别,match会进行文字分割。比如我们想查询“中国杭州”,那么match会分割成“中国”和“杭州”。会查询出包含“中国”或者“杭州”的数据。
但是match_phrase只会查询出包含了“中国杭州”的数据,并且中间不能被其他字符隔开。
多字段同条件查询
GET /test/article/_search
{
"query": {
"multi_match": {
"query": "这java",
"type": "best_fields",
"fields": [ "title", "content" ],
"minimum_should_match": "30%"
}
}
}
完全精确匹配
查询年龄为20的数据
GET /test/article/_search
{
"query": {
"term": {
"age": "20"
}
}
}
terms和term的区别:
term相当于mysql中的等于,而terms相当于mysql中的in
大于小于查询
GET /test/article/_search
{
"query": {
"range": {
"age": {
"gte": 20,
"lte": 25
}
}
}
}
- gte 大等于
- lte 小等于
获取当前所有的索引:
GET _cat/indices