1、pom文件导入ES依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.4.2</version>
</dependency>
2、编写配置,给容器中注入一个RestHighLevelClient
@Configuration
public class GulimallElasticSearchConfig {
public static final RequestOptions COMMON_OPTIONS;
static {
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
COMMON_OPTIONS = builder.build();
}
@Bean
public RestHighLevelClient esClient(){
RestClientBuilder builder = RestClient.builder(new HttpHost("192.168.146.129", 9200, "http"));
return new RestHighLevelClient(builder);
}
}
3、测试程序
@Test
public void indexData() throws IOException {
IndexRequest indexRequest = new IndexRequest("users");
// 数据ID
indexRequest.id("1");
User user = new User();
user.setUserName("zhangsan");
user.setGender("male");
user.setAge(20);
String jsonString = JSON.toJSONString(user);
indexRequest.source(jsonString, XContentType.JSON); // 要保存的内容
// 使用客户端执行操作
IndexResponse index = client.index(indexRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
System.out.println(index);
}
4、查看ES,数据已存入到ES
5、带检索条件的查询
@Test
public void searchData() throws IOException {
// 1、创建检索请求
SearchRequest searchRequest = new SearchRequest();
// 2、指定索引
searchRequest.indices("users");
// 3、指定DSL,检索条件
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 够造检索条件
sourceBuilder.query(QueryBuilders.matchQuery("userName", "zhangsan"));
searchRequest.source(sourceBuilder);
// 4、执行检索
SearchResponse searchResponse = client.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
System.out.println("---------> " + searchResponse);
}
打印结果:
{
"took": 5,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 0.2876821,
"hits": [
{
"_index": "users",
"_type": "_doc",
"_id": "1",
"_score": 0.2876821,
"_source": {
"age": 20,
"gender": "male",
"userName": "zhangsan"
}
}
]
}
}