Elasticsearch7.x 基本查询

本文主要介绍了Elasticsearch的基本查询。先说明了基本查询语法及查询类型,还提到需安装ik分词器。接着详细阐述了简单查询、match_all查询、term查询和match查询等,包括关键词查询、多关键词查询、分页查询等操作,以及分词结果对查询的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、Elasticsearch 基本查询

基本查询语法:

GET /索引名/_search
{
  "query": {
    "查询类型": {
      "查询属性": "查询条件值"
    }
  }
}

查询类型:match_all、term、match、match_phrasemulti_matchrange、fuzzy、bool 等

二、测试数据

Elasticsearch 需安装ik分词器,测试数据文章末尾。

三、基本查询

3.1、简单查询

1、查询所有

#查询所有
GET /item/_search

2、 简单查询

#简单查询
GET /item/_search?q=name:小米

3.2、match_all查询

match_all是查询全部

#查询所有
GET /item/_search
{
  "query": {
    "match_all": {}
  }
}

3.3、term查询

1、关键词查询

term是关键词查询,term里面的name值不进行分词

  • "name": "小米" :查询name属性包含"小米"的结果

  • "name": "小米手机" :查询name属性包含"小米手机"的结果

#关键词查询
GET /item/_search
{
	"query": {
		"term": {
			"name": "小米"
		}
	}
}

2、多关键词查询

多关键词查询,term里面的name值只要满足其中一个

  • "name": ["小米","apple"]:查询name属性包含"小米"或者"apple"的结果

 

#多关键词查询
GET /item/_search
{
	"query": {
		"terms": {
			"name": ["小米","apple"]
		}
	}
}

备注:

"name" : " Apple iPhone 12",其中Apple为首字母大写,如果term为Apple,查询结果为空

我们查看分词结果,发现 “Apple iPhone 12”的分词为"apple"、"iphone"、"12",所以用Apple 查不到分词结果为空。

3、查询结果包含版本号

"version": true:查询结果返回满足条件的记录时,包含版本号信息,每次修改该条记录,版本号会加1。

#查询结果包含版本号
GET /_search
{
  "version": true,
  "query": {
    "term": {
      "name": "小米"
    }
  }
}

4、分页查询

查询时,使用from和to进行分页查询,其中

  • "from": 分页起始位置
  • "size": 每页数据大小
#分页查询
GET /item/_search
{
  "query": {
    "term": {
        "category" : "手机"
    }
  },
  "from": 0,
  "size": 1
}


3.4、match查询

match查询是知道分词器存在的,先进行分词,再进行查询。

我们可以使用 GET _analyze 查看分词结果

  • "analyzer": 使用的分词器,ik 分词器有两种分词模式:ik_max_word 和 ik_smart 模式,这里使用的是ik_smart 模式
  • "text": 要进行分词的值
GET _analyze
{
  "analyzer": "ik_smart",
  "text": ["小米Redmi K30pro"]
}

1、关键字查询

先对match里面的name值进行分词,然后进行查询

  • "name": "小米手机" :分词结果为 "小米"、 "手机",查询name包含 "小米"和 "手机"的记录
#关键字分词查询
GET /item/_search
{
  "query": {
    "match": {
      "name": "小米手机"
    }
  }
}

关联查询

"小米Redmi K30pro"的分词结果为"小米"、"redmi"、"k30pro",查询条件"operator": "and",必须满足全部分词结果。

#关联查询
GET /item/_search
{
  "query": {
    "match": {
      "name": {
        "query": "小米Redmi K30pro",
        "operator": "and"
      }
    }
  }
}

查询条件"operator": "or",只需要满足其中一个分词结果。

#关联查询
GET /item/_search
{
  "query": {
    "match": {
      "name": {
        "query": "小米Redmi K30pro",
        "operator": "and"
      }
    }
  }
}

#多字段查询

#多字段查询
GET /item/_search
{
	"query": {
	  "multi_match": {
	    "query": "小米",
	    "fields": [ "name", "brand" ]
		}
	}
}

#短语查询

#短语查询
GET /item/_search
{
	"query": {
	  "match_phrase": {
	    "name": "Apple iPhone"
		}
	}
}

#短语查询
GET /item/_search
{
	"query": {
	  "match_phrase": {
	    "name": "Apple iPhone"
		}
	}
}

结果过滤

#结果过滤
GET /item/_search
{
  "_source": ["name","price"],
  "query": {
    "match": {
      "name": "小米"
    }
  }
}

结果过滤

#结果过滤
GET /item/_search
{
  "_source": {
    "excludes": ["images", "price"]
  },
  "query": {
    "match": {
      "name": "小米"
    }
  }
}

模糊查询

#模糊查询
GET /item/_search
{
  "query": {
    "fuzzy": {
      "name": "Apples"
    }
  }
}

范围查询

#范围查询
GET /item/_search
{
  "query": {
    "range": {
      "price":{
        "gt": 6000,
        "lte": 7000
      }
    }
  }
}

#通配符

#通配符查询
GET /item/_search
{
  "_source": {
    "excludes": ["cate*","*s"]
  },
  "query": {
    "match": {
      "name": "小米"
    }
  }
}

#前缀匹配

#前缀匹配查询
GET /item/_search
{
  "query": {
    "match_phrase_prefix": {
      "name": "小"
    }
  }
}

#范围查询

#范围查询
GET /item/_search
{
  "query": {
    "range": {
      "price":{
        "from": 5000,
        "to": 6999
      }
    }
  }
}

#范围查询不包含边界

#范围查询不包含边界
GET /item/_search
{
  "query": {
    "range": {
      "price":{
        "from": 5000,
        "to": 6999,
        "include_lower":false,
        "include_upper":false
      }
    }
  }
}

#通配符查询

#通配符查询
GET /item/_search
{
  "query": {
    "wildcard": {
      "category": "笔记本?"
    }
  }
}

 

#通配符查询
GET /item/_search
{
  "query": {
    "wildcard": {
      "category": "笔记本电?"
    }
  }
}

#通配符查询
GET /item/_search
{
  "query": {
    "wildcard": {
      "category": "笔记*"
    }
  }
}

must查询

#must查询
GET /item/_search
{
  "query": {
    "bool": {
      "must": [{
        "match": {
          "brand": "苹果"
        }
      },
      {
        "range": {
          "price": {
            "gt": 5000,
            "lte": 9000
          }
        }
      }]
    }
  }
}

should查询

#must查询
GET /item/_search
{
  "query": {
    "bool": {
      "should": [{
        "match": {
          "brand": "苹果"
        }
      },
      {
        "range": {
          "price": {
            "gt": 5000,
            "lte": 9000
          }
        }
      }]
    }
  }
}

must_not查询 范围查询影响分数

#must_not查询
GET /item/_search
{
  "query": {
    "bool": {
      "must_not": [{
        "match": {
          "brand": "小米"
        }
      },
      {
        "range": {
          "price": {
            "gt": 5000,
            "lte": 9000
          }
        }
      }]
    }
  }
}

过滤查询

#过滤查询
GET /item/_search
{
  "query": {
    "bool": {
      "should": [{
        "match": {
          "name": "苹果"
        }
      }],
      "filter": {
        "range": {
          "price": {
            "gt": 5000,
            "lte": 6000
          }
        }
      }
    }
  }
}

排序

#排序
GET /item/_search
{
  "query": {
    "match": {
      "brand": "苹果"
    }
  },
  "sort": [
    {
      "id": {
        "order": "desc"
      }
    }
  ]
}

PUT /item
{
  "mappings" : {
    "properties" : {
      "id" : {
        "type" : "long"
      },
      "name" : {
        "type" : "text",
        "analyzer" : "ik_smart"
      },
      "title" : {
        "type" : "text",
        "index": true, 
        "analyzer" : "ik_smart"
      },
      "price" : {
        "type" : "double"
      },
      "brand" : {
        "type" : "keyword"
      },
      
      "category" : {
        "type" : "keyword"
      },
      "images" : {
        "type" : "keyword",
        "index" : false
      }
    }
  },
  "settings" : {
    "index" : {
      "number_of_shards":3,
      "number_of_replicas":0
    }
  }
}

POST /item/_doc/1
{
	"id": 1,
	"name": "小米10至尊纪念版",
	"title": "小米10至尊纪念版 8G 256G 骁龙865",
	"brand": "小米",
	"category": "手机",
	"images": "https://img.jeespring.com/01.jpg",
	"price": 5699.00
}
POST /item/_doc/2
{
	"id": 2,
	"name": "Redmi K30 至尊纪念版",
	"title": "Redmi K30 至尊纪念版 天玑1000plus",
	"brand": "小米",
	"category": "手机",
	"images": "https://img.jeespring.com/02.jpg",
	"price": 2299.00
}

POST /item/_doc/3
{
	"id": 3,
	"name": " Apple iPhone 12",
	"title": "Apple iPhone 12 (A2404) 128GB 蓝色",
	"brand": "苹果",
	"category": "手机",
	"images": "https://img.jeespring.com/03.jpg",
	"price": 6999.00
}

POST /item/_doc/4
{
	"id": 4,
	"name": "荣耀智慧屏X1",
	"title": "荣耀智慧屏X1 65英寸2G+16G 4K超清",
	"brand": "华为",
	"category": "平板电视",
	"images": "https://img.jeespring.com/04.jpg",
	"price": 3699.00
}
POST /item/_doc/5
{
	"id": 5,
	"name": "联想ThinkBook 15p",
	"title": "联想ThinkBook 15p 十代i7 16G 512G",
	"brand": "联想",
	"category": "笔记本电脑",
	"images": "https://img.jeespring.com/05.jpg",
	"price": 7699.00
}
POST /item/_doc/6
{
	"id": 6,
	"name": "Apple MacBook Pro 16",
	"title": "Apple MacBook Pro 16 i7 16G 512G灰",
	"brand": "苹果",
	"category": "笔记本电脑",
	"images": "https://img.jeespring.com/06.jpg",
	"price": 16699.00
}

 

<think>好的,我现在需要帮助用户解决在Spring Boot 2.0中集成Elasticsearch 7.x的问题。首先,我需要确认用户的需求。他们想要一个教程解决方案,所以应该提供详细的步骤和可能的代码示例。 首先,我应该回想一下Spring Boot和Elasticsearch的版本兼容性。Spring Boot 2.0对应的Spring Data版本可能不是直接支持Elasticsearch 7.x的,因为通常Spring Data的版本和Elasticsearch的版本有对应关系。比如,Spring Boot 2.1.x之后才支持Elasticsearch 6.x,而更高的版本可能需要更高级的Spring Data。但用户想用Spring Boot 2.0,可能对应的Spring Data版本较旧,可能需要调整依赖使用其他方法。 接下来,我需要考虑如何让Spring Boot 2.0兼容Elasticsearch 7.x。可能的解决方案包括使用Elasticsearch的Java客户端,比如RestHighLevelClient,者通过覆盖依赖版本,使用与Elasticsearch 7.x兼容的Spring Data Elasticsearch版本。 另外,用户可能需要配置Elasticsearch的连接信息,比如主机和端口。在配置文件中设置spring.elasticsearch.rest.uris应该是一个步骤。 然后,可能需要创建实体类,使用@Document注解,以及定义Repository接口。这部分需要确保注解和Spring Data的版本兼容。如果Spring Boot 2.0的默认Spring Data版本不支持Elasticsearch 7.x的注解,可能需要手动调整使用不同的注解方式。 还可能涉及排除掉旧版的Elasticsearch客户端,比如TransportClient,并引入新的RestClient。这可以通过在MavenGradle中排除依赖并添加新的依赖项来实现。 测试部分,编写一个测试用例来验证连接是否成功,以及能否进行基本的CRUD操作,这也是用户需要的。 此外,需要注意版本冲突的问题,比如Jackson库其他依赖项的版本是否兼容。可能需要调整依赖版本以避免冲突。 最后,生成相关问题,比如兼容性问题、配置方法、版本差异、高级功能使用等,帮助用户进一步了解可能遇到的问题。 现在整理这些思路,形成结构化的回答,分步骤说明,并提供代码示例和配置示例。同时,确保引用之前的参考内容,虽然之前的引用是关于Spark的,但可能用户有其他相关问题,所以这里可能需要忽略无关引用,专注于当前问题。</think>### Spring Boot 2.0集成Elasticsearch 7.x的解决方案 #### 1. 版本兼容性调整 Spring Boot 2.0默认集成的Spring Data Elasticsearch版本较旧(通常为3.x),与Elasticsearch 7.x存在兼容性问题。需要通过Maven/Gradle手动指定兼容版本: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> <exclusions> <exclusion> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.17.3</version> <!-- 与ES服务端版本一致 --> </dependency> ``` #### 2. 配置客户端连接 在`application.properties`中配置: ```properties spring.elasticsearch.rest.uris=http://localhost:9200 spring.elasticsearch.rest.connection-timeout=5s spring.elasticsearch.rest.read-timeout=60s ``` 通过Java Config定义Bean: ```java @Configuration public class EsConfig { @Bean public RestHighLevelClient elasticsearchClient() { return new RestHighLevelClient( RestClient.builder(HttpHost.create("localhost:9200")) ); } } ``` #### 3. 实体映射 使用`@Document`注解定义索引映射: ```java @Document(indexName = "products", createIndex = false) public class Product { @Id private String id; @Field(type = FieldType.Text, analyzer = "ik_max_word") private String name; @Field(type = FieldType.Double) private Double price; // getters/setters } ``` #### 4. 仓库接口 继承`ElasticsearchRepository`: ```java public interface ProductRepository extends ElasticsearchRepository<Product, String> { List<Product> findByPriceBetween(Double min, Double max); } ``` #### 5. 自定义操作 通过`RestHighLevelClient`实现复杂查询: ```java @Autowired private RestHighLevelClient client; public SearchResponse searchByKeyword(String keyword) throws IOException { SearchRequest request = new SearchRequest("products"); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.matchQuery("name", keyword)); request.source(sourceBuilder); return client.search(request, RequestOptions.DEFAULT); } ``` #### 6. 测试验证 ```java @SpringBootTest class EsIntegrationTest { @Autowired private ProductRepository repository; @Test void testSaveDocument() { Product product = new Product(); product.setName("Spring Boot实战"); product.setPrice(59.99); Product saved = repository.save(product); assertNotNull(saved.getId()); } } ``` ### 关键注意事项 1. **版本矩阵**:需确保Spring Data ElasticsearchElasticsearch版本匹配[^1] 2. **类型映射**:ES 7.x已移除`_type`字段,需设置`@Document(indexName = "index")` 3. **分词器配置**:建议通过`@Setting`注解指定自定义分词器 4. **健康检查**:可通过`/actuator/health`端点监控ES连接状态
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值