Elasticsearch与java客户端交互的二种使用

一、原生Elasticsearch

1)导入依赖

<dependency>
   <groupId>org.elasticsearch.client</groupId>
   <artifactId>elasticsearch-rest-high-level-client</artifactId>
   <version>7.10.2</version>
</dependency>

2)创建索引

//索引管理
public class IndexManager {
    private RestHighLevelClient client;
    @Before
    public void init(){
        //创建一个client对象
        client =new RestHighLevelClient(RestClient.builder(
                new HttpHost("192.168.92.134",9200)
        ));
    }
    /**
     * 创建索引
     * @throws Exception
     */
    @Test
    public void creatIndex() throws Exception{

        //获取索引管理对象
        IndicesClient indicesClient = client.indices();
        //两个参数  2、请求选项 使用默认值 配置请求头、主要用于认证
        //1、创建索引请求对象 参数创建索引名称
        CreateIndexRequest request = new CreateIndexRequest("hello");
        CreateIndexResponse response = indicesClient.create(request, RequestOptions.DEFAULT);
        //显示结果
        System.out.println(response);
    }


     /**
     * 创建带有settings的索引
     * @throws Exception
     */
    @Test
    public void createIndex2() throws Exception{
        CreateIndexRequest request = new CreateIndexRequest("hello1").
                settings(Settings.builder().put("number_of_shards", 5).put("number_of_replicas", 1));
        client.indices().create(request,RequestOptions.DEFAULT);
    }
    /**
     * 创建带有settings和mappings的索引
     * @throws Exception
     */
    @Test
    public void createIndex3() throws Exception{
        XContentBuilder builder = XContentFactory.jsonBuilder()
                .startObject()//相当于json中的“{”
	                .startObject("properties")
	                .startObject("id")
	                .field("type","long")
                .endObject()//相当于json中的“}”
	                .startObject("title")
	                .field("type","text")
	                .field("analyzer","ik_smart")
	                .field("store",true)
                .endObject()
	                .startObject("content")
	                .field("type","text")
	                .field("analyzer","ik_smart")
	                .field("store",true)
                .endObject()
                .endObject()
                .endObject();
        CreateIndexRequest request = new CreateIndexRequest("hello3").
                settings(Settings.builder().put("number_of_shards", 5).put("number_of_replicas", 1).build()).mapping(builder);
        client.indices().create(request,RequestOptions.DEFAULT);

    }

    /**
     * 删除索引
     * @throws Exception
     */
    @Test
    public void delectIndex() throws Exception{
        client.indices().delete(new DeleteIndexRequest("hello"),RequestOptions.DEFAULT);
    }
    /**
     * 修改索引中的mappings
     * @throws Exception
     */
    @Test
    public void putMapping() throws Exception{
        String mappings = "{\n" +
                "  \"mappings\": {\n" +
                "    \"properties\": {\n" +
                "      \"id\":{\n" +
                "        \"type\": \"long\"\n" +
                "      },\n" +
                "      \"title\":{\n" +
                "        \"type\": \"text\",\n" +
                "        \"analyzer\": \"standard\"\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}\n";
        PutMappingRequest request = new PutMappingRequest("helle1")
                .source(mappings, XContentType.JSON);
        client.indices().putMapping(request,RequestOptions.DEFAULT);
    }
}

3)创建文档

//创建文档
public class DecumentManager {
    private RestHighLevelClient client;
    @Before
    public void init(){
        //创建一个client对象
        client =new RestHighLevelClient(RestClient.builder(
                new HttpHost("192.168.92.134",9200)
        ));
    }

    /**
     * 创建文档
     * @throws Exception
     */
    @Test
    public void addDecument() throws Exception{
        String document ="{\"id\":\"1\",\"title\":\"测试文档1\",\"concent\":\"测试文档内容\"}";
        //创建indexRequest对象,其中包含了索引名称文档id、文档内容
        IndexRequest indexRequest = new IndexRequest()
                .index("hello1")
                .id("1")
                .source(document, XContentType.JSON);
        client.index(indexRequest, RequestOptions.DEFAULT);
    }

    /**
     * 更新文档
     * @throws Exception
     */
    @Test
    public void updateDecument() throws Exception{
        String document ="{\"id\":\"1\",\"title\":\"测试1文档1\",\"concent\":\"测试文档内容\"}";

        UpdateRequest request = new UpdateRequest()
                .index("hello1")
                .id("1")
                .doc(document, XContentType.JSON);
        client.update(request,RequestOptions.DEFAULT);
    }
    @Test
    public void deleteDocument() throws Exception{
        DeleteRequest request = new DeleteRequest("hello1","1");
        client.delete(request,RequestOptions.DEFAULT);
    }

    /**
     * 查询文档
     * @throws Exception
     */
    @Test
    public void getDocument() throws Exception{
        GetRequest getRequest = new GetRequest("hello1","1");
        client.get(getRequest,RequestOptions.DEFAULT);
    }

    /**
     * 批量添加
     * @throws Exception
     */
    @Test
    public void bathDocument() throws Exception{
        String json = "[{\"id\":1, \"title\":\"帮日本核废水“出招”?知名男艺人迷之操作让人看呆了..\", \"content\":\"帮日本核废水“出招”?知名男艺人迷之操作让人看呆了..\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +
                "{\"id\":2, \"title\":\"《奔跑吧9》4月23日开播,沙溢、蔡徐坤等回归\", \"content\":\"《奔跑吧9》4月23日开播,沙溢、蔡徐坤等回归\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +
                "{\"id\":3, \"title\":\"桐梓:九坝这群人田间指导忙\", \"content\":\"桐梓:九坝这群人田间指导忙\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +
                                  "]";
        JSONArray jsonArray = JSONObject.parseArray(json);
        BulkRequest request = new BulkRequest();

        jsonArray.stream().forEach(j->{
            IndexRequest r = new IndexRequest()
                    .index("hello1")
                    .id(((JSONObject)j).getString("id"))
                    .source(((JSONObject)j).toJSONString(),XContentType.JSON);
            request.add(r);
        });
        client.bulk(request,RequestOptions.DEFAULT);
    }
}

3)查询索引

//查询索引内容
public class IndexSearch {
    private RestHighLevelClient client;
    @Before
    public void init(){
        //创建一个client对象
        client =new RestHighLevelClient(RestClient.builder(
                new HttpHost("192.168.92.134",9200)
        ));
    }

    /**
     * 查询所有
     * @throws Exception
     */
    @Test
    public void searchIndex() throws Exception{
        SearchRequest request = new SearchRequest("hello1")
                .source(new SearchSourceBuilder()
                .query(QueryBuilders.matchAllQuery()));//设置查询方式

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //从response对象中取出数据
        SearchHits searchHits =response.getHits();
        long total = searchHits.getTotalHits().value;
        System.out.println("查询的总计录数"+total);
        SearchHit[] searchHits1 = searchHits.getHits();
        Stream.of(searchHits1).forEach(e->{
            System.out.println(e);
        });

    }

    /**
     * 根据title进行查询
     * @throws Exception
     */
    @Test
    public void termSearch() throws Exception{
        SearchRequest request = new SearchRequest("hello1")
                .source(new SearchSourceBuilder()
                        .query(QueryBuilders.termQuery("title","品")));//设置查询方式

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);
    }
    public void printResult(SearchResponse response){
        //从response对象中取出数据
        SearchHits searchHits =response.getHits();
        long total = searchHits.getTotalHits().value;
        System.out.println("查询的总计录数"+total);
        SearchHit[] searchHits1 = searchHits.getHits();
        Stream.of(searchHits1).forEach(e->{
            System.out.println(e.getSourceAsString());
            System.out.println(e.getHighlightFields());
        });
    }

    /**
     * 设置分页信息
     * @throws Exception
     */
    @Test
    public void searchPage() throws Exception{
        SearchRequest request = new SearchRequest("hello1")
                .source(new SearchSourceBuilder()
                        //查询条件
                        .query(QueryBuilders.matchAllQuery())
                        //过滤
                        .postFilter(QueryBuilders.termQuery("title","品"))
                        //高亮显示
                        .highlighter(new HighlightBuilder()
                        .field("title").field("content")
                        .preTags("<em>")
                        .postTags("</em>"))
                        //分页条件
                        .from(0)
                        .size(30)
                );

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);
    }

}

二、使用SpringBoot的Elasticsearch

1)导入依赖

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
 </dependency>

设置对应自己的Elasticsearch的版本号

<elasticsearch.version>7.10.2</elasticsearch.version>

2)配置application配置文件

spring:
	 elasticsearch:
	    rest:
	      uris: xxx.xxx.xxx.xxx:9200//xx是自己的ip地址

3)创建实体类

@Data
@Document(indexName = "blog_1",shards = 5,replicas = 1)
public class Blog {
    @Id
    @Field(type = FieldType.Long,store = true)
    private Long id;
    @Field(type = FieldType.Text,analyzer = "ik_max_word",store = true)
    private String title;
    @Field(type = FieldType.Text,analyzer = "ik_max_word",store = true)
    private String content;
    @Field(type = FieldType.Text,analyzer = "ik_max_word",store = true)
    private String comment;
    @Field(type = FieldType.Text,store = true)
    private String mobile;
}

4)创建索引

@RunWith(SpringRunner.class)
@SpringBootTest(classes = DlmallSearchApplication.class)//因为在测试类给他设置启动
public class RestTemplateTest {
    @Autowired
    private ElasticsearchRestTemplate template;

    /**
     * 创建名为mytest的索引
     * @throws Exception
     */
    @Test
    public void createIndex() throws Exception{
        template.indexOps(IndexCoordinates.of("mytest")).create();
    }
    /**
     * 创建名为mytest的索引并设置mapping信息
     * @throws Exception
     */
    @Test
    public void putMapping(){
        Document mapping = template.indexOps(IndexCoordinates.of("mytest")).createMapping(Blog.class);
        template.indexOps(IndexCoordinates.of("mytest")).putMapping(mapping);
    }

    /**
     * 根据实体类对象创建mapping
     */
    @Test
    public void createIndexWithMapping(){
       // template.indexOps(Blog.class).create();
        Document mapping = template.indexOps(IndexCoordinates.of("mytest")).createMapping(Blog.class);

        template.indexOps(Blog.class).putMapping(mapping);
    }

    /**
     * 删除索引
     */
    @Test
    public void deleteIndex(){
        template.indexOps(IndexCoordinates.of("hello1")).delete();
    }

}

5)创建文档和查询文档

@RunWith(SpringRunner.class)
@SpringBootTest(classes= DlmallSearchApplication.class)
public class BlogRepositoryTest {

    @Autowired
    private BlogRepository blogRepository;

    /**
     * 根据实体类blog创建相对应得文档信息
     */
    @Test
    public void addDocument(){
        Blog blog = new Blog();
        blog.setId(1l);
        blog.setTitle("测试1");
        blog.setContent("neirong1");
        blog.setComment("内容");
        blog.setMobile("1111111111");
        blogRepository.save(blog);
    }

    /**
     * 更新文档
     */
    @Test
    public void updateDocument(){
        Optional<Blog> optional = blogRepository.findById(1l);
        if (optional.isPresent()){
            Blog blog = optional.get();
            blog.setTitle("hello word");

            blogRepository.save(blog);
        }
    }

    /**
     * 删除文档
     */
    @Test
    public void deleteDocument(){
        blogRepository.deleteById(1l);

    }

    /**
     * 根据id查询文档和查询全部进行分页
     */
    @Test
    public void getById(){
        Optional<Blog> optional = blogRepository.findById(1l);
        Blog blog = optional.get();
        System.out.println(blog);
        //分页
        Iterable<Blog> all = blogRepository.findAll(PageRequest.of(1, 10));
        all.forEach(e->{
            System.out.println(e);
        });
    }
}

6)使用批量

@RunWith(SpringRunner.class)
@SpringBootTest(classes= DlmallSearchApplication.class)
public class BulkTest {
    @Autowired
    private ElasticsearchRestTemplate template;

    /**
     * 批量添加索引文档内容
     */
    @Test
    public void bulkBlog(){
        JSONArray json = JSON.parseArray("[{\"id\":1, \"title\":\"帮日本核废水“出招”?知名男艺人迷之操作让人看呆了..\", \"content\":\"帮日本核废水“出招”?知名男艺人迷之操作让人看呆了..\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +
                "{\"id\":2, \"title\":\"《奔跑吧9》4月23日开播,沙溢、蔡徐坤等回归\", \"content\":\"《奔跑吧9》4月23日开播,沙溢、蔡徐坤等回归\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +
                "{\"id\":3, \"title\":\"桐梓:九坝这群人田间指导忙\", \"content\":\"桐梓:九坝这群人田间指导忙\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +
                "{\"id\":4, \"title\":\"柳子戏《江姐》进入联排阶段,月底将与济南观众见面\", \"content\":\"柳子戏《江姐》进入联排阶段,月底将与济南观众见面\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +
                 "]");
        List<IndexQuery> list = json.stream().map(query -> {
            IndexQuery indexQuery = new IndexQuery();
            indexQuery.setId(((JSONObject) query).getString("id"));
            indexQuery.setSource(((JSONObject) query).toJSONString());
            return indexQuery;
        }).collect(Collectors.toList());
        template.bulkIndex(list, IndexCoordinates.of("mytest"));
    }
    /**
     * 批量添加索引文档内容(使用实体类对象)
     */
    @Test
    public void bulkSaveBlog(){
        JSONArray json = JSON.parseArray("[{\"id\":1, \"title\":\"帮日本核废水“出招”?知名男艺人迷之操作让人看呆了..\", \"content\":\"帮日本核废水“出招”?知名男艺人迷之操作让人看呆了..\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +
                "{\"id\":2, \"title\":\"《奔跑吧9》4月23日开播,沙溢、蔡徐坤等回归\", \"content\":\"《奔跑吧9》4月23日开播,沙溢、蔡徐坤等回归\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +
                "{\"id\":3, \"title\":\"桐梓:九坝这群人田间指导忙\", \"content\":\"桐梓:九坝这群人田间指导忙\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +
                "]");
        List<Blog> list = json.stream().map(query -> {
            JSONObject jsonObject = (JSONObject) query;
            Blog blog = jsonObject.toJavaObject(Blog.class);
            return blog;
        }).collect(Collectors.toList());
        template.save(list);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Elasticsearch 提供了官方的 Java 客户,可以通过它与 Elasticsearch 服务器进行交互。下面是一个简单的示例,展示如何使用 Elasticsearch Java 客户: 1. 首先,确保你已经在项目中添加了 Elasticsearch Java 客户的依赖。你可以在 Maven 或 Gradle 中添加以下依赖项: Maven: ```xml <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.15.0</version> </dependency> ``` Gradle: ```groovy implementation 'org.elasticsearch.client:elasticsearch-rest-high-level-client:7.15.0' ``` 2. 在代码中创建 Elasticsearch 客户实例: ```java import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("localhost", 9200, "http"))); ``` 请确保将 "localhost" 和 9200 替换为你的 Elasticsearch 服务器的主机和口。 3. 使用客户执行操作,例如执行搜索操作: ```java import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.index.query.QueryBuilders; SearchRequest searchRequest = new SearchRequest("your_index_name"); searchRequest.source().query(QueryBuilders.matchQuery("your_field_name", "your_search_keyword")); SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); // 处理搜索响应 ``` 请将 "your_index_name" 替换为你的索引名称,将 "your_field_name" 替换为你要搜索的字段名称,将 "your_search_keyword" 替换为你要搜索的关键字。 这只是一个简单的示例,Elasticsearch Java 客户提供了丰富的 API,可用于执行各种操作,如索引文档、更新文档、删除文档等。你可以参考 Elasticsearch Java 客户的官方文档来了解更多信息:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值