code总结——java连接es(elasticsearch),进行增删改查

目录

java连接es,构建client

java控制es增删改查

1.查询

2.删除

3.更新

4.增加


java连接es,构建client

1.pom.xml ,构建maven依赖

 
    
      junit
      junit
      4.11
      test
    
      
          org.elasticsearch
          elasticsearch
          6.4.1
      
      
          org.elasticsearch.client
          transport
          6.2.4
      
      
          net.sf.json-lib
          json-lib
          2.4
          jdk15
      
  

2.在es安装目录config路径下的elasticsearch.yml设置集群名称:

code总结——java连接es(elasticsearch),进行增删改查_第1张图片

 3.连接es客户端代码:

package com.jia.connect;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import java.net.InetAddress;

public class esConnect {
    /**
     *
     * @return TransportClient
     * @throws Exception
     */
    public static final String IP ="localhost";
    public static final int PORT = 9300;
    @SuppressWarnings({"resource", "unchecked"})
    public static TransportClient getConnection() throws Exception {
        
        // 设置集群名称
        Settings settings = Settings.builder().put("cluster.name", "my-application").build();//es为集群名称
        // 创建client
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddresses(new TransportAddress(InetAddress.getByName(IP), PORT));

        System.out.println("es连接成功,获取连接对象: " + client.toString());
        return client;
        //client.close(); 使用完要close断开连接,释放资源
    }
}

                                                                                                                                       

java控制es增删改查

1.查询

 public static final String ESINDEX = "hongkong_article";
    public static final String ESTYPE = "hongkong_article";
    /**
     * 
     * @param client es连接客户端
     * @param queryField 查询字段
     * @param queryStr 查询字段值
     */
    public static void queryData(TransportClient client, String queryField ,String queryStr){
        QueryBuilder builder = QueryBuilders.matchQuery(queryField,queryStr);
        SearchResponse searchResponse = client.prepareSearch(ESINDEX)
                .setTypes(ESTYPE)
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(builder)
                .setSize(10)
                .get();
        SearchHit[] searchHits = searchResponse.getHits().getHits();
        for (SearchHit searchHit:searchHits){
            System.out.println(searchHit.getSourceAsString());
            String author = (String)searchHit.getSourceAsMap().get("author");
            String title = (String)searchHit.getSourceAsMap().get("title");
            String briefly = (String)searchHit.getSourceAsMap().get("briefly");
            String full_article_url = (String)searchHit.getSourceAsMap().get("full_article_url");
            String img_url = (String)searchHit.getSourceAsMap().get("img_url");
        }
    }

例子:

code总结——java连接es(elasticsearch),进行增删改查_第2张图片

2.删除

    /**
     * description 根据查询key=value结果删除数据
     * @param client TransportClient
     * @param key 
     * @param value
     */
    public static void deleteData (TransportClient client, String key ,String value){
        BulkByScrollResponse response = DeleteByQueryAction.INSTANCE.newRequestBuilder(client)
                .filter(QueryBuilders.matchQuery(key,value))
                .source("machine_class_2") //index
                .get();
        long deleted = response.getDeleted();
        System.out.print("delete where "+key+" = "+value+" : ");
        System.out.println(deleted==1);
    }

3.更新

根据查询字段进行局部更新,根据查询的内容找到待更新文档的id,然后进行更新

public class UpdateES {
    /**
     *
     * @param queryField 查找的字段
     * @param queryStr 查找字段的值
     * @param updateField 更新的字段
     * @param updateStr 更新字段的值
     * @throws IOException
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static void updateES(TransportClient client, String queryField ,String queryStr, String updateField, String updateStr) throws IOException, ExecutionException, InterruptedException {
        //TransportClient client = new EsUtils().getClient();
        String nameOfIndex = "hongkong_pic_new";
        String nameOfType = "hongkong_pic_new";
        QueryBuilder match = QueryBuilders.matchQuery(queryField,queryStr);

        SearchResponse res = client.prepareSearch(nameOfIndex)
                .setTypes(nameOfType)
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(match)
                .setSize(1)
                .get();

        String doc_id = res.getHits().getHits()[0].getId();//找到要更新的id
        System.out.println(doc_id);
        UpdateRequest request = new UpdateRequest();
        request.index(nameOfIndex) //索引名
                .type(nameOfType) //类型
                .id(doc_id)//id
                .doc(
                        XContentFactory.jsonBuilder()
                                .startObject()
                                .field(updateField, updateStr)//要修改的字段 及字段值
                                .endObject()
                );
        UpdateResponse response= client.update(request).get();
        System.out.println(response.status());

    }
}

举个例子:

code总结——java连接es(elasticsearch),进行增删改查_第3张图片

4.增加

待更新。。。

你可能感兴趣的:(elasticsearch,后端)