Spring boot集成elasticsearch原始方式

Spring boot集成elasticsearch原始方式

基础语法

1.配置文件

package config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @create 2020-11-20  15:16
 */
@Configuration

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

2.编写实体类

package com.entry;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @create 2020-11-20  15:49
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    
    private String name;
    private int age;
}

3.索引操作

package com.song.main;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
class MainApplicationTests {
    @Autowired
    public RestHighLevelClient client;
    //测试索引的创建
    @Test
    void testCreateIndex() throws IOException {
//1.创建索引的请求
        CreateIndexRequest request = new CreateIndexRequest("lisen_index");
        //2客户端执行请求,请求后获得响应
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(response);
    }

    //测试索引是否存在
    @Test
    void testExistIndex() throws IOException {
//1.创建索引的请求
        GetIndexRequest request = new GetIndexRequest("lisen_index");
        //2客户端执行请求,请求后获得响应
        boolean exist = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println("测试索引是否存在-----" + exist);
    }
    //删除索引
    @Test
    void testDeleteIndex() throws IOException {
    DeleteIndexRequest request = new DeleteIndexRequest("lisen_index");
    AcknowledgedResponse delete = client.indices().delete(request,RequestOptions.DEFAULT);
    System.out.println("删除索引--------"+delete.isAcknowledged());}
}

3.文档操作

package com.song.main;

import com.alibaba.fastjson.JSON;
import com.entry.User;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @create 2020-11-20  15:47
 */
@SpringBootTest
public class TestDoc {
    @Autowired
    public RestHighLevelClient client;


    @Test
    public void t(){
        System.out.println(123);
    }
    //测试添加文档
    @Test
    void testAddDocument() throws IOException {
        User user = new User("lisen",27);
        IndexRequest request = new IndexRequest("lisen_index");
        request.id("1");
        System.out.println(user.getName());
        //设置超时时间
        request.timeout("1s");
        //将数据放到json字符串
        request.source(JSON.toJSONString(user), XContentType.JSON);
        //发送请求
        IndexResponse response = client.index(request,RequestOptions.DEFAULT);
        System.out.println("添加文档-------"+response.toString());
        System.out.println("添加文档-------"+response.status());
    }

    //测试文档是否存在
    @Test
    void testExistDocument() throws IOException {
        //测试文档的 没有index
        GetRequest request= new GetRequest("lisen_index","1");
        //没有indices()了
        boolean exist = client.exists(request, RequestOptions.DEFAULT);
        System.out.println("测试文档是否存在-----"+exist);
    }

    //测试获取文档
    @Test
    void testGetDocument() throws IOException {
        GetRequest request= new GetRequest("lisen_index","1");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        System.out.println("测试获取文档-----"+response.getSourceAsString());
        System.out.println("测试获取文档-----"+response);

    }

    //测试修改文档
    @Test
    void testUpdateDocument() throws IOException {
        User user = new User("李逍遥", 55);
        //修改是id为1的
        UpdateRequest request= new UpdateRequest("lisen_index","1");
        request.timeout("1s");
        request.doc(JSON.toJSONString(user),XContentType.JSON);

        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        System.out.println("测试修改文档-----"+response);
        System.out.println("测试修改文档-----"+response.status());

}


    //测试删除文档
    @Test
    void testDeleteDocument() throws IOException {
        DeleteRequest request= new DeleteRequest("lisen_index","1");
        request.timeout("1s");
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        System.out.println("测试删除文档------"+response.status());
    }

    //测试批量添加文档
    @Test
    void testBulkAddDocument() throws IOException {
        ArrayList<User> userlist=new ArrayList<User>();
        userlist.add(new User("cyx1",5));
        userlist.add(new User("cyx2",6));
        userlist.add(new User("cyx3",40));
        userlist.add(new User("cyx4",25));
        userlist.add(new User("cyx5",15));
        userlist.add(new User("cyx6",35));
        //批量操作的Request
        BulkRequest request = new BulkRequest();
        request.timeout("1s");

        //批量处理请求
        for (int i = 0; i < userlist.size(); i++) {
            request.add(
                    new IndexRequest("lisen_index")
                            .id(""+(i+1))
                            .source(JSON.toJSONString(userlist.get(i)),XContentType.JSON)
            );
        }
        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
        //response.hasFailures()是否是失败的
        System.out.println("测试批量添加文档-----"+response.hasFailures());

    }


    //测试查询文档
    @Test
    void testSearchDocument() throws IOException {
        SearchRequest request = new SearchRequest("lisen_index");
        //构建搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //设置了高亮
        sourceBuilder.highlighter();
        //term name为cyx1的
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "cyx1");
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        request.source(sourceBuilder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        System.out.println("测试查询文档-----"+JSON.toJSONString(response.getHits()));
        System.out.println("=====================");
        List<Map> list=new ArrayList<>();
        for (SearchHit sh:response.getHits().getHits()) {
            Map<String, Object> sourceAsMap = sh.getSourceAsMap();
                HighlightField content = sh.getHighlightFields().get("text");
                if (content!=null){
                    Text[] fragments = content.fragments();
                    String newTitle = "";
                    for (Text text : fragments) {
                        newTitle +=text;
                    }
                    sourceAsMap.put("text",newTitle);//替换掉原来的内容
                }
            list.add(sourceAsMap);
        }}
        public boolean isExist(String text) throws IOException {
		List<String> list = new ArrayList<String>();
		Request request = new Request("GET", "_analyze");
		JSONObject entity = new JSONObject();
//		entity.put("analyzer", "ik_max_word"); 可以选择分词种类
		entity.put("analyzer", "ik_smart");
		entity.put("text", text);
		request.setJsonEntity(entity.toJSONString());
		Response response = client.getLowLevelClient().performRequest(request);
		JSONObject tokens = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
		JSONArray arrays = tokens.getJSONArray("tokens");
		String str = JSON.parseObject(arrays.getString(0)).getString("token");
		return !text.equals(str);
	}
	//判断分词是否存在
	public boolean isExist(String text) throws IOException {
		List<String> list = new ArrayList<String>();
		Request request = new Request("GET", "_analyze");
		JSONObject entity = new JSONObject();
//		entity.put("analyzer", "ik_max_word"); 可以选择分词种类
		entity.put("analyzer", "ik_smart");
		entity.put("text", text);
		request.setJsonEntity(entity.toJSONString());
		Response response = client.getLowLevelClient().performRequest(request);
		JSONObject tokens = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
		JSONArray arrays = tokens.getJSONArray("tokens");
		String str = JSON.parseObject(arrays.getString(0)).getString("token");
		return !text.equals(str);
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的 Spring Boot 集成 Elasticsearch 的示例: 1. 添加 Elasticsearch 依赖 在 `pom.xml` 文件中添加 Elasticsearch 的 Maven 依赖: ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> </dependencies> ``` 2. 配置 Elasticsearch 在 `application.properties` 中添加 Elasticsearch 的配置信息: ```properties # Elasticsearch 配置 spring.data.elasticsearch.cluster-name=my-application spring.data.elasticsearch.cluster-nodes=localhost:9300 ``` 3. 创建实体类 创建一个实体类,用于映射 Elasticsearch 中的一个文档: ```java import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; @Document(indexName = "books") public class Book { @Id private String id; private String title; private String author; // getter 和 setter 略 } ``` 4. 创建 Elasticsearch Repository 创建一个 Elasticsearch Repository,用于操作 Elasticsearch 中的文档: ```java import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; public interface BookRepository extends ElasticsearchRepository<Book, String> {} ``` 5. 使用 Elasticsearch Repository 在需要使用 Elasticsearch 的地方,注入 `BookRepository`,然后就可以对 Elasticsearch 中的文档进行操作了: ```java @Autowired private BookRepository bookRepository; public void addBook(Book book) { bookRepository.save(book); } public List<Book> searchBooks(String keyword) { return bookRepository.findByTitleContainingOrAuthorContaining(keyword, keyword); } public void deleteBook(String id) { bookRepository.deleteById(id); } ``` 以上就是一个简单的 Spring Boot 集成 Elasticsearch 的示例。当然,在实际使用中,还需要更多的配置和代码来支持更多的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值