Elasticsearch入门学习(四):使用javaAPI学习ES

一、Maven依赖

<!--刚开始少这个包创建索引失败    Validation Failed: 1: type is missing;   官方文档并没有给这个提示-->
    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>7.1.0</version>
    </dependency>
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>7.1.0</version>
    </dependency>

二、开始之前的准备

官方文档

/**
     * 连接ES
     * @return
     */
    public RestHighLevelClient start() {
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.100.151", 9201, "http"),
                        new HttpHost("192.168.100.151", 9202, "http"),
                        new HttpHost("192.168.100.151", 9203, "http")));
        return restHighLevelClient;
    }
 /**
 * 操作所用到的实体类
 */
@Data
class Article{
private long id;
private String title;
    public Article(long id, String title) {
        this.id = id;
        this.title = title;
    }
}

三、关于索引的操作

官方文档

  • 新增索引
public void createIndex(RestHighLevelClient client) {
        //索引名称
        CreateIndexRequest request = new CreateIndexRequest("hello");
        //分片副本
        request.settings(Settings.builder().put("index.number_of_shards", 5)
                .put("index.number_of_replicas", 1));
        //内容
        Map <String,Object> id = new HashMap <>();
        id.put("type","text");
        id.put("store",true);
        Map <String,Object> title = new HashMap <>();
        title.put("type","text");
        title.put("store",true);
        title.put("index",true);
        title.put("analyzer", "standard");
        Map <String,Object> properties = new HashMap <>();
        properties.put("id",id);
        properties.put("title",title);
        Map <String,Object> mapping = new HashMap <>();
        mapping.put("properties",properties);
        request.mapping(mapping);
        try {
            CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
            System.out.println(response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  • 查询指定索引
public void getIndex(RestHighLevelClient client) throws IOException {
    //索引名称
    GetIndexRequest request = new GetIndexRequest("hello");
    try {
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  • 删除索引
public void delIndex(RestHighLevelClient client){
    DeleteIndexRequest request = new DeleteIndexRequest("hello");
    try {
        AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

四、关于文档的操作

官方文档

  • 创建文档
public void createDocument(RestHighLevelClient client){
        //索引名称
        IndexRequest indexRequest = new IndexRequest("hello");
        ObjectMapper mapper = new ObjectMapper();
        Article article = new Article(3L, "web前端");
        byte[] json = new byte[0];
        try {
            json = mapper.writeValueAsBytes(article);
            //可以设置文章ID
            indexRequest.id("5");
            indexRequest.source(json, XContentType.JSON);
            IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • 根据文档ID查询文档
public void getDocument(RestHighLevelClient client){
    GetRequest getRequest = new GetRequest("hello", "1");
    GetResponse documentFields = null;
    try {
        documentFields = client.get(getRequest, RequestOptions.DEFAULT);
        System.out.println(documentFields.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  • 更新文档
public void updateDocument(RestHighLevelClient client){
        UpdateRequest  updateRequest = new UpdateRequest("hello", "1");
        Article article = new Article(2L, "java入门到放弃");
        ObjectMapper mapper = new ObjectMapper();
        byte[] json = new byte[0];
        try {
            json = mapper.writeValueAsBytes(article);
            IndexRequest indexRequest = new IndexRequest("hello");
            indexRequest.source(json, XContentType.JSON);
            updateRequest.doc(indexRequest);
            UpdateResponse updateResponse = client.update(
                    updateRequest, RequestOptions.DEFAULT);
            System.out.println(updateResponse);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • 删除文档
public void delDocument(RestHighLevelClient client){
        DeleteRequest request = new DeleteRequest("hello", "1");
        try {
            DeleteResponse deleteResponse = client.delete(
                    request, RequestOptions.DEFAULT);
            System.out.println(deleteResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  • 查询文档
public void searchDocument(RestHighLevelClient client){
        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = null;
        try {
            searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            System.out.println(searchResponse.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

相关推荐