DBA Elasticsearch 文档查询

基础搜索

空搜索

​ 返回所有索引下的所有文档:

GET /_search

​ 当然这种操作会返回kibana的内置索引。

多类型搜索

​ 返回指定索引下的多个类型中的所有文档:

PUT /user/userinfo/1
{
  "name" : "Jack",
  "age"  : 19,
  "class" : 1
}

PUT /class/classinfo/1
{
  "name" : "三年级一班",
  "number_of_people" : 30
}

GET /class,user/userinfo,classinfo/_search

ID搜索

​ 返回指定ID的文档:

GET /user/userinfo/1

条件搜索

​ 返回指定条件的文档:

GET /test_index/userinfo/_search?q=name:jack

​ 或者可以使用更加强大的方式:

GET /test_index/userinfo/_search
{
    "query":{
        "match":{
               "name":"jack"
         }
    }
}

# match中指定条件

image-20210405122951430

进阶搜索

特定字段

​ 只显示特定的字段,通过/_source进行:

GET /test_index/userinfo/_search
{
	"query":{
		"match":{
		  "name":"jack"
		}
	},
	"_source": ["name", "age"]
}

字段排序

​ 在匹配分数排序的基础上,按照字段再次进行排序:

GET /test_index/userinfo/_search
{
	"query":{
		"match":{
		  "name":"jack"
		}
	},
	"sort": [
	  {
	    "age": {
	      "order": "desc"
	    }
	  }
	]
}

分页搜索

​ 指定搜索分页:

GET /test_index/userinfo/_search
{
	"query":{
		"match":{
		  "name":"jack"
		}
	},
  "from": 0,
  "size": 10
}

# from:类似于limit的第一个值,从拿开始拿,以0开始
# size:类似于limit的第二个值,拿几个

条件搜索

​ 使用bool进行多条件搜索,下面是官网示例:

{
    "bool": {
        "must":     { "match": { "tweet": "elasticsearch" }},
        "must_not": { "match": { "name":  "mary" }},
        "should":   { "match": { "tweet": "full text" }},
        "filter":   { "range": { "age" : { "gt" : 30 }} }
    }
}

# must:必须满足,相当于where and
# must_not:筛选不满足的,相当于NOT
# should:多个满足其一即可,相当于OR
# filter:过滤,配合range可用gt/lt/gte/lte等进行查询

​ 示例演示:

GET /test_index/userinfo/_search
{
  "query": {
    "bool": {
      "must": [
        {"match": {"name": "jack"}},
        {"match": {"age": "18"}}
      ],
      "must_not": [
        {"match":{"gender":2}}
      ]
    }
  }
}

# SELECT * FROM test_index.userinfo
# WHERE name = "jack" and age = "18" and "gender" != 2
# 一个match中只能有一个条件,但可以多个分开

多值匹配

​ 一次性匹配多个,相当于IN条件,tags是一个数组,只要包含吃饭睡觉的都会筛选出来:

GET /test_index/userinfo/_search
{
	"query": {
		"match":{
			"tags" : "吃饭 睡觉"
		}
	}
}

精确匹配

​ match是会将词进行拆分后匹配,而term则是直接对词进行精确匹配。

​ 如果match匹配都field类型是keyword,则不会进行分词操作。

GET /test_index/userinfo/_search
{
  "query": {
    "term": {
      "name": "jack"
    }
  }
}

高亮查询

​ 对搜索的关键词进行高亮显示,可使用highlight进行词汇筛选:

GET /test_index/userinfo/_search
{
  "query": {
    "match": {
      "name": "jack"
    }
  },
  "highlight": {
    "pre_tags": "<mark>",
    "post_tags": "</mark>", 
    "fields": {
      "name":{}
    }
  }
}

​ 查询结果:

image-20210405160353630

posted @ 2021-04-05 16:09  云崖君  阅读(52)  评论(0编辑  收藏  举报