1. 程式人生 > >elasticsearch-6.4.3 java程式碼操作ES

elasticsearch-6.4.3 java程式碼操作ES

elasticsearch-6.4.3 java程式碼操作ES

     這次我講的是6.4.3版本的elasticsearch相關java程式碼,其餘版本的elasticsearch用這套程式碼不一定會好使,所以說看的時候請注意你的elasticsearch版本號和我的版本號是否相同,如果不同的話,估計這套程式碼對你基本沒啥作用。

    在貼程式碼之前先說下elasticsearch幾個關鍵的屬性由那些

  1.  近實時查詢
  2. 節點和叢集
  3. 文件
  4. 索引
  5. 型別
  6. 分片和複製

具體的概念和elasticsearch的安裝配置就不說了,百度一搜一大把,我就直接上程式碼了。

   /**
     * 初始化客戶端連線
     */

private static TransportClient client;
   
 public Client initESClient() {
        // 配置你的es,如果你的叢集名稱不是預設的elasticsearch,需要以下這步
        Settings settings = Settings.builder().put("cluster.name","elasticsearch")
                .put("client.transport.ignore_cluster_name", true)
                .build();
        // 這裡可以同時連線叢集的伺服器,可以多個,並且連線服務是可訪問的
        try {
            // 建立client
            client = new PreBuiltTransportClient(settings)

                    .addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.1.112"), 9300))
            ;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }finally
        {
            if(client != null)
            {
                System.out.println("連線成功!");
            }
        }
        return client;
    }

     /**
     * 關閉客戶端連線
     */     

    public void closeESClient() {
        client.close();
        System.out.println("連線關閉!");
    }

    /**
     * 建立索引
     */

    @SuppressWarnings("unused")
    private void createIndex() {
        try {
            //建立對映
             //title:欄位名,  type:文字型別       analyzer :分詞器型別
            XContentBuilder mapping = jsonBuilder()
                    .startObject()
                    .startObject("properties")
                    .startObject("title").field("type", "text").field("analyzer", "ik_smart").endObject()   //該欄位新增的內容,查詢時將會使用ik_smart分詞
                    .startObject("content").field("type", "text").field("analyzer", "ik_max_word").endObject()
                    .endObject()
                    .endObject();
            //index:索引名   type:型別名(可以自己定義)
            PutMappingRequest putmap = Requests.putMappingRequest("yzy").type("type").source(mapping);
            //建立索引
            client.admin().indices().prepareCreate("yzy").execute().actionGet();
            //為索引新增對映
            client.admin().indices().putMapping(putmap).actionGet();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 新增資料
     * **/

    public void addIndex()throws IOException{
               try{
                   //prepareIndex(索引,文字型別,ID)
                   IndexResponse response = client.prepareIndex("yzy", "type", "1")
                           .setSource(jsonBuilder()
                                   .startObject()
                                   .field("title", "標題")   //欄位,值
                                   .field("content", "內容")
                                   .endObject()
                           ).get();

               }catch (Exception e){
                   e.printStackTrace();
               }
    }

    /**
     * 更新索引
     * **/

    public void updateByClient() throws IOException, ExecutionException, InterruptedException {
        //每次新增id應該不同,相當於資料表中的主鍵,相同 的話將會進行覆蓋
        UpdateResponse response = client.update(new UpdateRequest("yzy", "type", "1")
                .doc(XContentFactory.jsonBuilder()
                        .startObject()
                        .field("title", "標題1")
                        .field("content","Hello world!!!")
                        .endObject()
                )).get();
    }

    /**
     * 獲取指定文件
     * index 索引
     * type  型別
     * idtype   id
     */


    public Map<String,Object> get(String index,String type,String idtype){
        GetResponse response = client.prepareGet(index, type,idtype).get();
        Map<String, Object> source = response.getSource();
        Set<String> strings = source.keySet();
        Iterator<String> iterator = strings.iterator();
        while (iterator.hasNext()) {
            System.out.println(source.get(iterator.next()));
        }
       return source;

    }

 /**
     * 搜尋索引            例子
     * index索引          school_index
     * type 型別          doc
     * query 屬性         address
     * cxz   查詢值       西城
     */

    public List<Map<String,Object>> search(String index,String type,String query,String cxz){
        final  List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        SearchResponse sr = client.prepareSearch()  //指定多個索引
                .setTypes(index, type)  //指定型別
                .setSearchType(SearchType.QUERY_THEN_FETCH)
                .setQuery(QueryBuilders.matchQuery(query, cxz))  // Query
                .setFrom(0).setSize(60).setExplain(true)
                .get();
        long totalHits1= sr.getHits().totalHits;  //命中個數
        for (SearchHit searchHit : sr.getHits().getHits()) {
            final Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
            list.add(sourceAsMap);
        }
        System.out.println(totalHits1+"---"+sr.toString());
        return list;
    }

    /**
     * 刪除
     */

    public void delete(){
        //DeleteResponse response = client.prepareDelete("customertest", "joey", "1").get();  //刪除文件
        //刪除索引
        DeleteIndexResponse deleteIndexResponse = client.admin().indices()
                .prepareDelete("yzy")
                .execute().actionGet();
        boolean isFound = deleteIndexResponse.isAcknowledged();
        System.out.println(isFound);//返回文件是否存在,存在刪除
    }

    /**
     * 批量新增
     */

    public void bulkdoc() throws IOException
    {
        BulkRequestBuilder bulkRequest = client.prepareBulk();
        bulkRequest.add(client.prepareIndex("twitter", "tweet", "1")
                .setSource(jsonBuilder()
                        .startObject()
                        .field("user", "kimchy")
                        .field("postDate", new Date())
                        .field("message", "trying out Elasticsearch")
                        .endObject()
                )
        );

        bulkRequest.add(client.prepareIndex("twitter", "tweet", "2")
                .setSource(jsonBuilder()
                        .startObject()
                        .field("user", "kimchy")
                        .field("postDate", new Date())
                        .field("message", "another post")
                        .endObject()
                )
        );

        BulkResponse bulkResponse = bulkRequest.get();
        if (bulkResponse.hasFailures()) {
            // process failures by iterating through each bulk response item
        }

    }

 /**
     * 全文查詢(根據屬性值查詢)
     * query  屬性名
     * msg   查詢值
     * **/

 public List<Map<String,Object>> searchZd(String query,String msg){
        Map<String, Object> template_params = new HashMap<String, Object>();
        template_params.put("param_gender", msg);
        template_params.put("param_query", query);
        final  List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        //模板查詢
        SearchResponse sr = new SearchTemplateRequestBuilder(client)
                .setScript("{\n" +
                        "        \"query\" : {\n" +
                        "            \"match\" : {\n" +
                        "                \"{{param_query}}\" : \"{{param_gender}}\"\n" +
                        "            }\n" +
                        "        }\n" +
                        "}")
                .setScriptType(ScriptType.INLINE)
                .setScriptParams(template_params)
                .setRequest(new SearchRequest())
                .get()
                .getResponse();
        long totalHits1= sr.getHits().totalHits;  //命中個數
        for (SearchHit searchHit : sr.getHits().getHits()) {
            final Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
            list.add(sourceAsMap);
        }
        System.out.println(totalHits1+"---"+sr.toString());
        return list;
    }

   /**
     * 全文查詢
     * msg   查詢值
     * **/

public List<Map<String,Object>> searchEs(String msg){
        Map<String, Object> template_params = new HashMap<String, Object>();
        template_params.put("param_gender", msg);
        final  List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        //模板查詢
        SearchResponse sr = new SearchTemplateRequestBuilder(client)
                .setScript("{\n" +
                        "        \"query\" : {\n" +
                        "            \"query_string\" : {\n" +
                        "                \"query\" : \"{{param_gender}}\"\n" +
                        "            }\n" +
                        "        }\n" +
                        "}")
                .setScriptType(ScriptType.INLINE)
                .setScriptParams(template_params)
                .setRequest(new SearchRequest())
                .get()
                .getResponse();
        long totalHits1= sr.getHits().totalHits;  //命中個數
        for (SearchHit searchHit : sr.getHits().getHits()) {
            final Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
            list.add(sourceAsMap);
        }
        System.out.println(totalHits1+"---"+sr.toString());
        return list;
    }