ES API

更新

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.ExecutionException;

/**
 * @author liubosong
 * @version 1.0
 * @date 2019/11/22 7:41 下午
 **/
public class App {
    TransportClient client;

    /**
     * 获取客户端对象
     *
     * @throws UnknownHostException
     */
    @Before
    public void getClient() throws UnknownHostException {
        Settings settings = Settings.builder().put("cluster.name", "elasticsearch_liubosong").build();

        client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300));
//        System.out.println(client.toString());
    }

    @Test
    public void createIndices() {
        /**
         * 创建索引
         * 关闭资源
         */
        client.admin().indices().prepareCreate("blog").get();
        client.close();
    }

    @Test
    public void deleteIndices() {
        client.admin().indices().prepareDelete("blog").get();
        client.close();
    }

    @Test
    public void createIndexByJson() {
        /**
         * indices 相当于数据库
         * index 实际文档的具体索引的创建 一些列的
         */
        String json = "{" + "\"id\":\"1\"," + "\"title\": \"基于Lucene的搜索服务器\" ,"
                + "\"content\": \"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口\"" + "}";

        /**
         * 新版本不再适用,转为map
         */
        JSONObject jsonObject = JSON.parseObject(json);
        client.prepareIndex("blog", "article", "1").setSource(jsonObject).execute().actionGet();
        client.close();
    }

    @Test
    public void createIndexByMap() {
        HashMap<String, Object> json = new HashMap<>();
        json.put("id", "2");
        json.put("title", "建设");
        json.put("content", "欣赏内容");
        client.prepareIndex("blog", "article", "2").setSource(json).execute().actionGet();
        client.close();
    }

    @Test
    public void createIndexByBuilder() throws IOException {
        XContentBuilder builder = XContentFactory.jsonBuilder()
                .startObject()
                .field("id", 4)
                .field("title", "jack")
                .field("content", "fuck")
                .endObject();

        IndexResponse response = client.prepareIndex("blog", "article", "3")
                .setSource(builder).execute().actionGet();
        client.close();
    }

    @Test
    public void queryIndex() {
        GetResponse response = client.prepareGet("blog", "article", "1").get();
        System.out.println(response.getSourceAsString());
        client.close();
    }

    @Test
    public void queryMultiIndex() {
        MultiGetResponse response = client.prepareMultiGet()
                .add("blog", "article", "1")
                .add("blog", "article", "2")
                .add("blog", "article", "3")
                .get();
        Iterator<MultiGetItemResponse> iterator = response.iterator();
        while (iterator.hasNext()) {
            MultiGetItemResponse res = iterator.next();
            System.out.println(res.getResponse().getSourceAsString());
        }
        client.close();
    }

    @Test
    public void update() throws IOException, ExecutionException, InterruptedException {
        UpdateRequest updateRequest = new UpdateRequest("blog", "article", "1");
        XContentBuilder updateRes = XContentFactory.jsonBuilder()
                .startObject()
                .field("id", "2")
                .field("title", "建设")
                .field("content", "go go go")
                .endObject();
        updateRequest.doc(updateRes);
        client.update(updateRequest).get();
    }


    @Test
    public void delete() {
        // 删除文档
        client.prepareDelete("blog", "article", "1").get();
        client.close();
    }

    @Test
    public void searchMatchAll() {
        // search query
        SearchResponse searchResponse = client.prepareSearch("blog")
                .setTypes("article")
                .setQuery(QueryBuilders.matchAllQuery())
                .get();
        // 获取文档
        SearchHits hits = searchResponse.getHits();
        System.out.println(hits.getTotalHits());

        Iterator<SearchHit> iterator = hits.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next().getSourceAsString());
        }
        client.close();
    }

    @Test
    public void searchMatchString() {
        // search query
        SearchResponse searchResponse = client.prepareSearch("blog")
                .setTypes("article")
                .setQuery(QueryBuilders.queryStringQuery("fuck"))
                .get();

        Iterator<SearchHit> iterator = searchResponse.getHits().iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next().getSourceAsString());
        }
        client.close();
    }

    @Test
    public void searchMatchWildcard() {
        // search query
        SearchResponse searchResponse = client.prepareSearch("blog")
                .setTypes("article")
                .setQuery(QueryBuilders.wildcardQuery("content", "*fuck*"))
                .get();

        Iterator<SearchHit> iterator = searchResponse.getHits().iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next().getSourceAsString());
        }
        client.close();
    }

    @Test
    public void fuzzy() {
        // search query fuzzy
        SearchResponse searchResponse = client.prepareSearch("blog")
                .setTypes("article")
                .setQuery(QueryBuilders.fuzzyQuery("title", "jack"))
                .get();

        Iterator<SearchHit> iterator = searchResponse.getHits().iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next().getSourceAsString());
        }
        client.close();
    }

    @Test
    public void createMapping() throws Exception {
        // 1设置mapping
        XContentBuilder builder = XContentFactory.jsonBuilder()
                .startObject()
                .startObject("article")
                .startObject("properties")
                .startObject("id1")
                .field("type", "string")
                .field("store", "yes")
                .endObject()
                .startObject("title2")
                .field("type", "string")
                .field("store", "no")
                .endObject()
                .startObject("content")
                .field("type", "string")
                .field("store", "yes")
                .endObject()
                .endObject()
                .endObject()
                .endObject();
        // 2 添加mapping
        PutMappingRequest mapping = Requests.putMappingRequest("blog4").type("article").source(builder);
        // 创建mapping 必须是之前没有mapping的索引 才可以 如果已经存在 则不可以
        // 没有blog4 要新建
        client.admin().indices().putMapping(mapping).get();
        // 3 关闭资源
        client.close();
    }

}

  

ES API

上一篇:Windows7安装PowerShell5.1方法(Flutter新版本需要)


下一篇:C#读取音频文件