ElasticSearch分布式搜索引擎_高级查询
本文承接自
高级查询
1.1布尔组合(bool)
bool
把各种其它查询通过must
(与)、must_not
(非)、should
(或)的方式进行组合
GET /testindex511/_search
{
"query":{
"bool":{
"must": { "match": { "title": "大米" }},
"must_not": { "match": { "title": "电视" }},
"should": { "match": { "title": "手机" }}
}
}
}
"大米"匹配到一定命中
"电视"匹配到一定排除
"手机"命中,此时如果是"手机电视"则一定排除,其他都命中
1.2范围查询(range)
range
查询找出那些落在指定区间内的数字或者时间
GET /testindex511/_search
{
"query":{
"range": {
"price": {
"gte": 1000.0,
"lt": 2800.00
}
}
}
}
range
查询允许以下字符
操作符 | 说明 |
---|---|
gt | 大于 |
gte | 大于等于 |
lt | 小于 |
lte | 小于等于 |
本例中
字段大于等于1000.0与小于2000.0的文档都会被查询出来
1.3模糊查询(fuzzy)
向我们的索引中新增一条数据
POST /testindex511/goods/4
{
"title":"apple手机",
"images":"http://image.leyou.com/12479122.jpg",
"price":6899.00
}
查询条件如下
GET /testindex511/_search
{
"query": {
"fuzzy": {
"title": "appla"
}
}
}
返回结果
{
"took": 31,
"timed_out": false,
"_shards": {
"total": 3,
"successful": 3,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 0.23014566,
"hits": [
{
"_index": "testindex511",
"_type": "goods",
"_id": "4",
"_score": 0.23014566,
"_source": {
"title": "apple手机",
"images": "http://image.leyou.com/12479122.jpg",
"price": 6899
}
}
]
}
}
appla也能查询到apple手机
"fuzziness":1
此属性可以指定偏差距离
过滤(filter)
在之前,我们是使用
"_source"进行结果过滤,但
所有的查询都会影响到文档的评分及排名。如果我们需要在查询结果中进行过滤,并且不希望过滤条件影响评分,那么就不要把过滤条件作为查询条件来用。而是使用filter
方式:
GET /testindex511/_search
{
"query":{
"bool":{
"must":{ "match": { "title": "小米手机" }},
"filter":{
"range":{"price":{"gt":2000.00,"lt":3800.00}}
}
}
}
}
如果一次查询只有过滤,没有查询条件,不希望进行评分,我们可以使用constant_score
取代只有 filter 语句的 bool 查询。在性能上是完全相同的,但对于提高查询简洁性和清晰度有很大帮助
GET /testindex511/_search
{
"query":{
"constant_score": {
"filter": {
"range":{"price":{"gt":2000.00,"lt":3000.00}}
}
}
}}
排序(sort)
sort
可以让我们按照不同的字段进行排序,并且通过order
指定排序的方式
GET /testindex511/_search
{
"query": {
"match": {
"title": "小米手机"
}
},
"sort": [
{
"price": {
"order": "desc"
}
}
]
}
本例将所有"小米"字段按价格desc降序,asc为升序
假定我们想要结合使用 price和 _score(得分) 进行查询,并且匹配的结果首先按照价格排序,然后按照相关性得分排序:
GET /testindex511/_search
{
"query":{
"bool":{
"must":{ "match": { "title": "小米手机" }},
"filter":{
"range":{"price":{"gt":2000,"lt":3000}}
}
}
},
"sort": [
{ "price": { "order": "desc" }},
{ "_score": { "order": "desc" }}
]
}