elastic search 查询

时间:2021-12-06 17:08:23

eelastic search主要有两种查询方式,一种是查询字符串,一种是请求体(json格式)查询。

查询字符串:

查询字符串的功能相对简单,使用容易。

比如GET http://localhost:9200/list/doc/_search,直接在游览器地址栏输入以上地址,elastic search会返回json格式字符串,意思是查询所有list索引下面类型为doc的文档。

那如果我是 GET http://localhost:9200/_search呢?没错就是在查询所有索引所有类型中的文档,值得一提的是elastic search 将在7以后版本取消类型(type)这一概念。

现在假如我有这样格式的文档(导入bank索引详细见我关于logstash导入elastic search的博客)

{
"_index": "bank",
"_type": "account",
"_id": "25",
"_version": 1,
"_score": 1,
"_source": {
"account_number": 25,
"balance": 40540,
"firstname": "Virginia",
"lastname": "Ayala",
"age": 39,
"gender": "F",
"address": "171 Putnam Avenue",
"employer": "Filodyne",
"email": "virginiaayala@filodyne.com",
"city": "Nicholson",
"state": "PA"
}
}

我想查找 firstname下面名为Virginia的所有账户,那么可以使用如下查询字符串

GET http://localhost:9200/bank/account/_search?q=firstname:Virginia

返回结果

{
"took": 7,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 4.882802,
"hits": [
{
"_index": "bank",
"_type": "account",
"_id": "25",
"_score": 4.882802,
"_source": {
"account_number": 25,
"balance": 40540,
"firstname": "Virginia",
"lastname": "Ayala",
"age": 39,
"gender": "F",
"address": "171 Putnam Avenue",
"employer": "Filodyne",
"email": "virginiaayala@filodyne.com",
"city": "Nicholson",
"state": "PA"
}
}
]
}
}
如果我想找firstname为Virginia,lastname为Ayala的人,可以用如下查询字符串
GET http://localhost:9200/bank/account/_search?q=firstname:Virginia+lastname:Ayala
 
如果我们想要一些更加复杂的查询,那么就要采用请求体查询了
比如 GET http://localhost:9200/bank/account/_search?q=firstname:Virginia+lastname:Ayala
在请求体查询中是这样的

GET /bank/account/_search
{
"query": {
"bool": {
"must":[
{ "match": { "firstname": "Virginia" }},
{ "match": { "lastname": "Ayala" }}
]
}
}
}