springBoot 整合 ElasticSearch

SpringBoot 整合ElasticSearch

1.创建一个Springboot 的项目,导入依赖

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.62</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

2.编写ElasticSearch的配置类ElasticsearchClientConfig

@Configuration
public class ElasticsearchClientConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                new HttpHost("127.0.0.1", 9200, "http")));
        return client;
    }

}

3.创建实体类User

@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class User {
    private String name;
    private int age;
}

4.测试常用方法

对索引的操作

@SpringBootTest
class EstestApplicationTests {
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    @Test
    void contextLoads() throws IOException {
        //创建索引请求
        CreateIndexRequest request = new CreateIndexRequest("yang_index");
        //
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse);

    }
    @Test
    void contextLoads1() throws IOException {
        //获取索引
        GetIndexRequest request = new GetIndexRequest("yang_index");
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);

    }

    @Test
    void contextLoads2() throws IOException {
        //删除索引
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest();

        AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        System.out.println(delete);

    }
}

对文档的操作

  • 添加文档
//添加文档
void contextLoads3() throws IOException {
        //添加文档
        User user = new User("张三", 12);
        IndexRequest request = new IndexRequest("yang_index");

        request.id("1");
        request.timeout(TimeValue.timeValueSeconds(1));

        request.source(JSON.toJSONString(user), XContentType.JSON);

        IndexResponse index = client.index(request, RequestOptions.DEFAULT);
        System.out.println(index.toString());
        System.out.println(index.status());
    }
  • 获取文档,判断是否存在
void contextLoads4() throws IOException {
        //获取文档,判断是否存在
        GetRequest request = new GetRequest("yang_index", "1");

        boolean exists = client.exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }
  • 获取文档信息
void contextLoads5() throws IOException {
        //获取文档信息
        GetRequest request = new GetRequest("yang_index", "1");

        GetResponse getResponse = client.get(request, RequestOptions.DEFAULT);
        System.out.println(getResponse.getSourceAsString());
        System.out.println(getResponse);
    }
  • 更新文档信息
 void contextLoads6() throws IOException {
        //更新文档记录
        UpdateRequest request = new UpdateRequest("yang_index", "1");
        request.timeout("1s");
        User user = new User("李四", 21);
        request.doc(JSON.toJSONString(user), XContentType.JSON);
        UpdateResponse update = client.update(request,RequestOptions.DEFAULT);
        System.out.println(update.status());

    }
  • 删除文档
 void contextLoads7() throws IOException {
        //删除文档
        DeleteRequest request = new DeleteRequest("yang_index", "1");
        request.timeout("1s");
        DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.status());
    }
  • 批量添加
void contextLoads8() throws IOException {
        //批量
        BulkRequest bulkRequest = new BulkRequest();
        ArrayList<User> userArrayList = new ArrayList<User>();
        userArrayList.add(new User("Zhangsan0",4));
        userArrayList.add(new User("Zhangsan1",3));
        userArrayList.add(new User("Zhangsan2",8));
        userArrayList.add(new User("Zhangsan4",13));
        userArrayList.add(new User("Zhangsan5",23));
        userArrayList.add(new User("Zhangsan6",33));
        userArrayList.add(new User("Zhangsan7",43));

        for (int i = 0; i < userArrayList.size(); i++) {
            bulkRequest.add(
                    new IndexRequest("yang_index")
                    .id(""+(i+1))
                    .source(JSON.toJSONString(userArrayList.get(i)),XContentType.JSON)
            );
        }

        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulk.hasFailures());
    }
  • 根据某字段来搜索
 void contextLoads9() throws IOException {
        SearchRequest searchRequest = new SearchRequest("yang_index");

        SearchSourceBuilder builder = new SearchSourceBuilder();
//        QueryBuilders.matchAllQuery(); //匹配所有
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "李四");
        builder.query(termQueryBuilder);

        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        searchRequest.source(builder);

        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);

        System.out.println(JSON.toJSONString(search.getHits()));

        for (SearchHit hit : search.getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值