栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

ElasticSearch JavaApi

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ElasticSearch JavaApi

1、SpringBoot整合ES

①搭建SpringBoot工程

②引入ElasticSearch相关坐标


        
            org.elasticsearch.client
            elasticsearch-rest-high-level-client
            7.4.0
        
        
            org.elasticsearch.client
            elasticsearch-rest-client
            7.4.0
        
        
            org.elasticsearch
            elasticsearch
            7.4.0
        

创建application.yml(方便读取IP与端口号)

elasticsearch:
  host: IP地址
  port: 9200

③测试

ElasticSearchConfig

@Configuration
@ConfigurationProperties(prefix="elasticsearch") // 这个注解通过前缀名获取到yml中的数据
public class ElasticSearchConfig {

    private String host;

    private int port;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
    @Bean
    public RestHighLevelClient client(){
        return new RestHighLevelClient(RestClient.builder(
                new HttpHost(host,port,"http")
        ));
    }
}

ElasticsearchDay01ApplicationTests

注意:使用@Autowired注入RestHighLevelClient 如果报红线,则是因为配置类所在的包和测试类所在的包,包名不一致造成的2、

@SpringBootTest
class ElasticsearchDay01ApplicationTests {

    @Autowired
    RestHighLevelClient client;

    
    @Test
    void contextLoads() {

        System.out.println(client);
    }
}
2、创建索引 2.1、添加索引
    @Test
    public void addIndex() throws IOException {
       //1.使用client获取操作索引对象
        IndicesClient indices = client.indices();
        //2.具体操作获取返回值
        //2.1 设置索引名称
        CreateIndexRequest createIndexRequest=new CreateIndexRequest("itheima");

        CreateIndexResponse createIndexResponse = indices.create(createIndexRequest, RequestOptions.DEFAULT);
        //3.根据返回值判断结果
        System.out.println(createIndexResponse.isAcknowledged());
    }
2.2、添加索引,并添加映射
    @Test
    public void addIndexAndMapping() throws IOException {
       //1.使用client获取操作索引对象
        IndicesClient indices = client.indices();
        //2.具体操作获取返回值
        //2.具体操作,获取返回值
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("itcast");
        //2.1 设置mappings
        String mapping = "{n" +
                "      "properties" : {n" +
                "        "address" : {n" +
                "          "type" : "text",n" +
                "          "analyzer" : "ik_max_word"n" +
                "        },n" +
                "        "age" : {n" +
                "          "type" : "long"n" +
                "        },n" +
                "        "name" : {n" +
                "          "type" : "keyword"n" +
                "        }n" +
                "      }n" +
                "    }";
        createIndexRequest.mapping(mapping,XContentType.JSON);

        CreateIndexResponse createIndexResponse = indices.create(createIndexRequest, RequestOptions.DEFAULT);
        //3.根据返回值判断结果
        System.out.println(createIndexResponse.isAcknowledged());
    }
3、查询、删除、判断索引 3.1、查询索引
    @Test
    public void queryIndex() throws IOException {
        IndicesClient indices = client.indices();

        GetIndexRequest getRequest=new GetIndexRequest("itcast");
        GetIndexResponse response = indices.get(getRequest, RequestOptions.DEFAULT);
        Map mappings = response.getMappings();
        //iter 提示foreach
        for (String key : mappings.keySet()) {
            System.out.println(key+"==="+mappings.get(key).getSourceAsMap());
        }
    }
3.2、删除索引
 
    @Test
    public void deleteIndex() throws IOException {
         IndicesClient indices = client.indices();
        DeleteIndexRequest deleteRequest=new DeleteIndexRequest("itheima");
        AcknowledgedResponse delete = indices.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());

    }
3.3、索引是否存在
 
    @Test
    public void existIndex() throws IOException {
        IndicesClient indices = client.indices();

        GetIndexRequest getIndexRequest=new GetIndexRequest("itheima");
        boolean exists = indices.exists(getIndexRequest, RequestOptions.DEFAULT);


        System.out.println(exists);

    }
4、添加文档 4.1、添加文档,使用map作为数据
 @Test
    public void addDoc1() throws IOException {
        Map map=new HashMap<>();
        map.put("name","张三");
        map.put("age","18");
        map.put("address","北京二环");
        IndexRequest request=new IndexRequest("itcast").id("1").source(map);
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.out.println(response.getId());
    }
4.2、添加文档,使用对象作为数据
@Test
public void addDoc2() throws IOException {
    Person person=new Person();
    person.setId("2");
    person.setName("李四");
    person.setAge(20);
    person.setAddress("北京三环");
    String data = JSON.toJSONString(person); // 这里使用了fastjson的方法,所以我们还要导入fastjson依赖包
    IndexRequest request=new IndexRequest("itcast").id(person.getId()).source(data,XContentType.JSON);
    IndexResponse response = client.index(request, RequestOptions.DEFAULT);
    System.out.println(response.getId());
}
5、修改、查询、删除文档 5.1、修改文档:添加文档时,如果id存在则修改,id不存在则添加

    @Test
    public void UpdateDoc() throws IOException {
        Person person=new Person();
        person.setId("2");
        person.setName("李四");
        person.setAge(20);
        person.setAddress("北京三环车王");
        
        //将对象转为json
        String data = JSON.toJSONString(person);

        //1.获取操作文档的对象
        IndexRequest request=new IndexRequest("itcast").id(person.getId()).source(data,XContentType.JSON);
        //添加数据,获取结果
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        //打印响应结果
        System.out.println(response.getId());
    }
5.2、根据id查询文档
 
    @Test
    public void getDoc() throws IOException {

        //设置查询的索引、文档
        GetRequest indexRequest=new GetRequest("itcast","2");

        GetResponse response = client.get(indexRequest, RequestOptions.DEFAULT);
        System.out.println(response.getSourceAsString());
    }
5.3、根据id删除文档
    @Test
    public void delDoc() throws IOException {

        //设置要删除的索引、文档
        DeleteRequest deleteRequest=new DeleteRequest("itcast","1");

        DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(response.getId());
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/825503.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号