ElasticSearch8.X 查询相关

DBC 425 0

1.创建索引

PUT /shop_v1
{
  "settings": {
    "number_of_shards": 2,
    "number_of_replicas": 0
  },
  "mappings": {
    "properties": {
      "id": {
        "type": "keyword"
      },
      "title": {
        "type": "keyword"
      },
      "summary": {
        "type": "text"
      },
      "price": {
        "type": "float"
      }
    }
  }
}

2.添加基本数据

PUT /shop_v1/_bulk
{ "index": { "_index": "shop_v1" } }
{ "id": "1", "title": "Spring Boot","summary":"this is a summary Spring Boot video", "price": 9.99 }
{ "index": { "_index": "shop_v1" } }
{ "id": "2", "title": "java","summary":"this is a summary java video", "price": 19.99 }
{ "index": { "_index": "shop_v1" } }
{ "id": "3", "title": "Spring Cloud","summary":"this is a summary Spring Cloud video", "price": 29.99 }
{ "index": { "_index": "shop_v1" } }
{ "id": "4", "title": "Spring_Boot", "summary":"this is a summary Spring_Boot video","price": 59.99 }
{ "index": { "_index": "shop_v1" } }
{ "id": "5", "title": "SpringBoot","summary":"this is a summary SpringBoot video", "price": 0.99 }
  • 查询全部数据(match_all)
    • 是一种简单的查询,匹配索引中的所有文档
    • GET /shop_v1/_search
      {
        "query": {
          "match_all": {}
        }
      }
      
  • 有条件查询数据
    • match,对查询内容进行分词, 然后进行查询,多个词条之间是 or的关系
    • 然后在与文档里面的分词进行匹配,匹配度越高分数越高越前面
    • GET /shop_v1/_search
      {
        "query": {
          "match": {
            "summary": "Spring"
          }
        }
      }
      
      GET /shop_v1/_search
      {
        "query": {
          "match": {
            "summary": "Spring Java"
          }
        }
      }
  • 完整关键词查询
    • term查询,不会将查询条件分词,直接与文档里面的分词进行匹配
    • 虽然match也可以完成,但是match查询会多一步进行分词,浪费资源
    • #keyword类型字段,ES不进行分词
      GET /shop_v1/_search
      {
        "query": {
          "term": {
            "title": {
              "value": "Spring Boot"
            }
          }
        }
      }

 

  • 获取指定字段
    • 某些情况场景下,不需要返回全部字段,太废资源,可以指定source返回对应的字段
    • GET /shop_v1/_search
      {
      "_source":["price","title"],
        "query": {
          "term": {
            "title": {
              "value": "Spring Boot"
            }
          }
        }
      }

 

  • 总结
    • match在匹配时会对所查找的关键词进行分词,然后分词匹配查找;term会直接对关键词进行查找
    • 一般业务里面需要模糊查找的时候,更多选择match,而精确查找时选择term查询

发表评论 取消回复
表情 图片 链接 代码

分享