search api的基本语法
语法概要:
GET /_search
{}
GET /index1,index2/type1,type2/_search
{}
GET /_search { "from": 0, "size": 10 }
http协议中get是否可以带上request body?
HTTP协议,一般不允许get请求带上request body,但是因为get更加适合描述查询数据的操作,因此还是这么用了。
很多浏览器,或者是服务器,也都支持GET+request body模式
如果遇到不支持的场景,也可以用POST /_search
GET /_search?from=0&size=10 POST /_search { "from":0, "size":10 }
query DSL
一个例子让你明白什么是query DSL
GET /_search { "query": { "match_all": {} } }
Query DSL的基本语法
GET /{index}/_search/{type}
{
"各种条件"
}
示例:
GET /test_index/test_type/_search { "query": { "match": { "test_field": "test" } } } { "took": 1, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 3, "max_score": 0.843298, "hits": [ { "_index": "test_index", "_type": "test_type", "_id": "6", "_score": 0.843298, "_source": { "test_field": "test test" } }, { "_index": "test_index", "_type": "test_type", "_id": "8", "_score": 0.43445712, "_source": { "test_field": "test client 2" } }, { "_index": "test_index", "_type": "test_type", "_id": "7", "_score": 0.25316024, "_source": { "test_field": "test client 1" } } ] } }
组合多个搜索条件
搜索需求:title必须包含elasticsearch,content可以包含elasticsearch也可以不包含,author_id必须不为111
构造数据:
PUT /website/article/1 { "title":"my elasticsearch article", "content":"es is very bad", "author_id":110 } PUT /website/article/2 { "title":"my hadoop article", "content":"hadoop is very bad", "author_id":111 } PUT /website/article/3 { "title":"my hadoop article", "content":"hadoop is very good", "author_id":111 }
组合查询:
GET /website/article/_search { "query": { "bool": { "must": [ { "match": { "title": "elasticsearch" } } ], "should": [ { "match": { "content": "elasticsearch" } } ], "must_not": [ { "match": { "author_id": 111 } } ] } } }
查询结果:
{ "took": 7, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 1, "max_score": 0.25316024, "hits": [ { "_index": "website", "_type": "article", "_id": "1", "_score": 0.25316024, "_source": { "title": "my elasticsearch article", "content": "es is very bad", "author_id": 110 } } ] } }