ElasticSearch基础api的使用

独自空忆成欢 提交于 2020-03-01 14:19:26

1.首先创建 RestHighLevelClient 对象 因为后面的操作都需要这个

@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class SpringConfig {

    @Value("${elasticsearch.host}")
    private String host;
    @Value("${elasticsearch.port}")
    private Integer port;

    @Bean
    public RestHighLevelClient restHighLevelClient() throws Exception {
        return new RestHighLevelClient(RestClient.builder(new HttpHost(host,port)));
    }

}

在application里配置 

elasticsearch:
  host: 192.168.149.135
  port: 9200

2.常用api的使用

在对索引进行操作的时候  需要创建IndicesClient indicesClient = client.indices();

对文档则直接使用client 即可

@SpringBootTest
class ElasticsearchDemoApplicationTests {

    @Autowired
    private RestHighLevelClient client;

 

    /**
     * 添加索引
     */
    @Test
    public void addIndex() throws IOException {
        //1.使用client获取操作索引的对象
        IndicesClient indicesClient = client.indices();
        //2.具体操作,获取返回值
        CreateIndexRequest createRequest = new CreateIndexRequest("索引名称");
        CreateIndexResponse response = indicesClient.create(createRequest, RequestOptions.DEFAULT);

        //3.根据返回值判断结果
        System.out.println(response.isAcknowledged());
    }


    /**
     * 添加索引和mapping   ***修改和添加一样的 默认如果有当前索引和mapping 则不处理 如果没有则覆盖
     */
    @Test
    public void addIndexAndMapping() throws IOException {
        //1.使用client获取操作索引的对象
        IndicesClient indicesClient = client.indices();
        //2.具体操作,获取返回值
        CreateIndexRequest createRequest = new CreateIndexRequest("索引名称");
        //2.1 设置mappings
        String mapping = "mappings数据";
		//给索引绑定mapping
        createRequest.mapping(mapping,XContentType.JSON);

        //执行添加数据并获得返回值
        CreateIndexResponse response = indicesClient.create(createRequest, RequestOptions.DEFAULT);

        //3.根据返回值判断结果
        System.out.println(response.isAcknowledged());



    }


    /**
     * 查询索引
     */
    @Test
    public void queryIndex() throws IOException {
		
		
        IndicesClient indices = client.indices();

        GetIndexRequest getReqeust = new GetIndexRequest("索引名称");
		
        GetIndexResponse response = indices.get(getReqeust, RequestOptions.DEFAULT);


        //获取结果
        Map<String, MappingMetaData> mappings = response.getMappings();
        for (String key : mappings.keySet()) {
            System.out.println(key+":" + mappings.get(key).getSourceAsMap());

        }

    }


    /**
     * 删除索引
     */
    @Test
    public void deleteIndex() throws IOException {
	
        IndicesClient indices = client.indices();

        DeleteIndexRequest deleteRequest = new DeleteIndexRequest("索引名称");
		
        AcknowledgedResponse response = indices.delete(deleteRequest, RequestOptions.DEFAULT);

        System.out.println(response.isAcknowledged());

    }

    /**
     * 判断索引是否存在
     */
    @Test
    public void existIndex() throws IOException {
        IndicesClient indices = client.indices();

        GetIndexRequest getRequest = new GetIndexRequest("索引名称");
		
        boolean exists = indices.exists(getRequest, RequestOptions.DEFAULT);

        System.out.println(exists);

    }


    /**
     * 添加文档,使用map作为数据
     */
    @Test
    public void addDoc() throws IOException {
        //数据对象,map
        Map data = new HashMap();
        data.put("address","北京昌平");
        data.put("name","大胖");
        data.put("age",20);


        //1.获取操作文档的对象
        IndexRequest request = new IndexRequest("索引名称").id("文档id").source(data);
        //添加数据,获取结果
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);

      

    }


    /**
     * 添加文档,使用对象作为数据
     */
    @Test
    public void addDoc2() throws IOException {
        //数据对象,javaObject
        Person p = new Person();
        p.setId("2");
        p.setName("小胖2222");
        p.setAge(30);
        p.setAddress("陕西西安");

        //将对象转为json
        String data = JSON.toJSONString(p);

        //1.获取操作文档的对象
        IndexRequest request = new IndexRequest("itcast").id(p.getId()).source(data,XContentType.JSON);
        //添加数据,获取结果
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);

        //打印响应结果
        System.out.println(response.getId());


    }


    /**
     * 修改文档:添加文档时,如果id存在则修改,id不存在则添加
     */
    @Test
    public void updateDoc() throws IOException {

    }



    /**
     * 根据id查询文档
     */
    @Test
    public void findDocById() throws IOException {

        GetRequest getReqeust = new GetRequest("索引名称","文档id");
        //getReqeust.id("1");
        GetResponse response = client.get(getReqeust, RequestOptions.DEFAULT);
        //获取数据对应的json
        System.out.println(response.getSourceAsString());


    }



    /**
     * 根据id删除文档
     */
    @Test
    public void delDoc() throws IOException {


        DeleteRequest deleteRequest = new DeleteRequest("索引名称","文档id");
        DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(response.getId());


    }

}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!