首页 > 其他分享 >ElasticSearch中查询(排序、高亮、分页、Filter过滤、_source筛选)

ElasticSearch中查询(排序、高亮、分页、Filter过滤、_source筛选)

时间:2022-11-24 23:26:27浏览次数:51  
标签:search GET title Filter source ElasticSearch query match

排序(sort)

sort可以让我们按照不同的字段进行排序,并且通过order指定排序的方式

  • asc升序
  • desc倒序
GET my_index/_search
{
  "query": {
    "match": {
      "title": "小米电视"
    }
  },
  "sort": [
    {
      "price": {
        "order": "desc"
      }
    }
  ]
}

 

 

 

 

高亮(highlight)

 高亮是在搜索结果中把搜索关键字标记出来,因此必须使用match这样的分词搜索

语法

GET /heima/_search
{
  "query": {
    "match": {
      "title": "手机"
    }
  },
  "highlight": {
    "pre_tags": "<em>",
    "post_tags": "</em>", 
    "fields": {
      "title": {}
    }
  }
}

在使用match查询的同时,加上一个highlight的属性:

pre_tags:前置标签,可以省略,默认是em

post_tags:后置标签,可以省略,默认是em

fields:需要高亮的字段

title:这里声明title字段需要高亮,后面可以为这个字段设置特有配置,也可以空

例子:

GET my_index/_search
{
  "query": {
    "match": {
      "title": "小米"
    }
  },
  "highlight": {
    "pre_tags": "<em>", 
    "post_tags": "</em>", 
    "fields": {
      "title": {}
    }
  }
}

 

 

 

分页(from、size)

通过from和size来指定分页的开始位置和每页大小

GET my_index/_search
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "price": {
        "order": "desc"
      }
    }
  ], 
  "from": 0,
  "size": 2
}

 

Filter过滤

 

当我们在京东这样的电商网站购物,往往查询条件不止一个,还会有很多过滤条件

而在默认情况下,所有的查询条件、过滤条件都会影响打分和排名,而对搜索结果打分是比较影响性能的,因此我们一般只对用户输入的条件对应的字段打分,其他过滤项不打分,此时就不能简单使用布尔查询的must来组合条件了,而是使用filter方式,

例如

我们要查询小米,同时对价格过滤,原本的写法是这样的

GET my_index/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "title": "小米"
          }
        },
        {
          "range": {
            "price": {
              "gte": 3000
            }
          }
        }
      ]
    }
  }
}

现在要修改成这样

GET my_index/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "title": "小米"
          }
        }
      ],
      "filter": {
        "range": {
          "price": {
            "gte": 3000
          }
        }
      }
    }
  }
}

 

 

 

_source筛选

默认情况下,elasticsearch在搜索的结果中,会把文档中保存在_source的所有字段都返回,如果我们只想获取其中的部分字段,我们可以添加_source的过滤

GET my_index/_search
{
  "_source": ["title", "price"],
  "query": {
    "match": {
      "title": "小米"
    }
  }
}

 

 

 

指定includes和excludes

我们也可以通过:

  • includes:来指定想要显示的字段
  • excludes:来指定不想要显示的字段

2者都是可选的

示例:

GET my_index/_search
{
  "_source": ["title", "price"],
  "query": {
    "match": {
      "title": "小米"
    }
  }
}

与下面的结果将是一样的

GET my_index/_search
{
  "_source": {
    "includes": ["title", "price"]
  },
  "query": {
    "match": {
      "title": "小米"
    }
  }
}

  

  

标签:search,GET,title,Filter,source,ElasticSearch,query,match
From: https://www.cnblogs.com/xulinjun/p/16923817.html

相关文章