首页 > 编程语言 >java引入es使用

java引入es使用

时间:2024-05-10 19:33:06浏览次数:23  
标签:java void client IOException 引入 new type throws es

引入依赖

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>

初始化对象

RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
        HttpHost.create("http://192.168.150.101:9200")
));

 索引CRUD操作

public class ElasticIndexTest {
    private RestHighLevelClient client;
    @BeforeEach
    void setUp(){
        client=new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.88.95",9200,"http")));
    }

    @AfterEach
    void tearDown() throws IOException {
        if(client!=null)
            client.close();
    }

    @Test
    void create() throws IOException {
        CreateIndexRequest test = new CreateIndexRequest("hmall");
        test.source(MAPPING_TEMPLATE, XContentType.JSON);
        client.indices().create(test, RequestOptions.DEFAULT);
    }
    @Test
    void get() throws IOException {
        GetIndexRequest test = new GetIndexRequest("hmall");
        client.indices().get(test, RequestOptions.DEFAULT);
    }
    @Test
    void delete() throws IOException {
        DeleteIndexRequest test = new DeleteIndexRequest("hmall");
        client.indices().delete(test, RequestOptions.DEFAULT);
    }
    private final static String MAPPING_TEMPLATE="{\n" +
            "  \"mappings\": {\n" +
            "    \"properties\": {\n" +
            "      \"id\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"name\":{\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_smart\"\n" +
            "      },\n" +
            "      \"price\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"image\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"category\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"brand\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"sold\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"comment_count\":{\n" +
            "        \"type\": \"integer\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"isAD\":{\n" +
            "        \"type\": \"boolean\"  \n" +
            "      },\n" +
            "      \"update_time\":{\n" +
            "        \"type\": \"date\"\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";
}

文档CRUD操作

public class ElasticDocumentTest {
    @Autowired
    private IItemService service;
    private RestHighLevelClient client;
    @BeforeEach
    void setUp(){
        client=new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.88.95",9200,"http")));
    }

    @AfterEach
    void tearDown() throws IOException {
        if(client!=null)
            client.close();
    }

    /* 新增
     * 全量修改:写入重复ID即视为全量修改
     * */
    @Test
    void addAndUpdateDoc() throws IOException {
        Item byId = service.getById("317578");
        ItemDoc itemDoc = BeanUtil.copyProperties(byId, ItemDoc.class);

        IndexRequest request=new IndexRequest("hmall").id(itemDoc.getId());
        request.source(JSONUtil.toJsonStr(itemDoc),XContentType.JSON);
        client.index(request,RequestOptions.DEFAULT);
    }
    /*局部修改*/
    @Test
    void updateDoc() throws IOException {
        UpdateRequest request=new UpdateRequest("hmall","317578");
        request.doc(
                "price","25600"
        );
        client.update(request,RequestOptions.DEFAULT);
    }
    /*查询*/
    @Test
    void getDoc() throws IOException {
        GetRequest getRequest=new GetRequest("hmall","317578");
        GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);
        String json = response.getSourceAsString();
        ItemDoc itemDoc = JSONUtil.toBean(json, ItemDoc.class);
    }
    /*删除*/
    @Test
    void deleteDoc() throws IOException {
        DeleteRequest deleteRequest=new DeleteRequest("hmall","317578");
        client.delete(deleteRequest, RequestOptions.DEFAULT);

    }
}

文档批处理操作:

    /*批处理*/
    @Test
    void bulkDoc() throws IOException {
        int pageSize=500;
        int pageNum=1;
        while(true){
            Page<Item> page = service.lambdaQuery()
                    .eq(Item::getStatus, 1)
                    .page(Page.of(pageNum, pageSize));
            List<Item>items=page.getRecords();
            if(items==null||items.isEmpty()){
                return;
            }
            BulkRequest request=new BulkRequest();

            for (Item item : items) {
                request.add(new IndexRequest("hmall")
                        .id(item.getId().toString())
                        .source(JSONUtil.toJsonStr(BeanUtil.copyProperties(item, ItemDoc.class)),XContentType.JSON)
                );
            }
            client.bulk(request,RequestOptions.DEFAULT);
            pageNum++;
        }


    }

 

标签:java,void,client,IOException,引入,new,type,throws,es
From: https://www.cnblogs.com/kun1790051360/p/18184010

相关文章

  • ResultMap结果集映射
    为什么需要用到ResultMap?它可以将查询到的复杂数据(比如查询到几个表中数据)映射到一个结果集当中,设置灵活,应用广泛。应用在数据库字段信息与对象属性不一致或者需要做复杂的联合查询以便自由控制映射结果。简单的映射(建立SQL查询结果字段与实体属性的映射关系)publicclass......
  • JAVA 启动常用命令
    nohupjava-jarxxx.jar&--运行jar文件ssh关闭也继续运行nohupjava-jar-Xms512m-Xmx1024mxxx.jar&--指定内存运行jar文件ssh关闭也继续运行nohupjava-jar-Xms512m-Xmx1024m&nohupjava-Dfile.encoding=utf-8-jar-Xms512m-Xmx1024m&以utf-8编码......
  • 深入探索JavaScript中的structuredClone:现代深拷贝的解密指南
    在JavaScript中,实现深拷贝的方式有很多种,每种方式都有其优点和缺点。今天介绍一种原生JavaScript提供的structuredClone实现深拷贝。下面列举一些常见的方式,以及它们的代码示例和优缺点:1.使用JSON.parse(JSON.stringify(obj))代码示例:functiondeepClone(obj){re......
  • sqlSession相关的作用域和生命周期
    生命周期和作用域是十分重要的,错误的使用会导致非常严重的并发问题。Mybatis的执行流程详细讲解SqlSessionFactoryBuilder:一旦创建了SqlSessionFactory,就不需要它了,比较适合在局部变量中创建。SqlSessionFactory:相当于数据库的连接池;SqlSessionFactory一旦被创建就应......
  • Java web基础
    1、理解Jsp的page指令JSP(JavaServerPages)中的<%@page%>指令用于设置整个JSP页面的属性。它通常位于JSP页面的顶部,用于指定页面的一些配置信息。生存周期仅限制在本页面。2、理解Jsp的include指令在JSP中,<%@include%>指令用于在一个JSP页面中包含另一个文件的内容。这个指......
  • Codeforces 1146D Frog Jumping
    首先根据裴蜀定理,能走到的点\(x\)肯定满足\(\gcd(a,b)|x\)。于是令\(g=\gcd(a,b)\),可以考虑求解\(\lfloor\frac{m}{g}\rfloor,\frac{a}{g},\frac{b}{g}\),最后记得去判一下\([g\lfloor\frac{m}{g}\rfloor,m]\)这个区间,因为只有这个区间是不满(区间长度可能\(<g\)......
  • Spring Cloud 部署时如何使用 Kubernetes 作为注册中心和配置中心
    一、SpringCloud支持的常见注册中心和配置中心。SpringCloud自带的注册中心Eureka以及config配置中心Nacos,支持注册中心和配置中心等,可以参考:https://www.cnblogs.com/laoqing/p/17797759.htmlZookeeperConsulEtcdKubernetes,当SpringCloud服务都是通过Kubernetes部......
  • NetSuite-Get-specific-Custom-Record-Types-and-related-sub-Custom-Fields-CarlZeng
    NetSuite:GetspecificCustomRecordTypesandrelatedsubCustomFields背景以前当使用search.create({})来获取数据时,我们需要制定特定的数据返回列;例如:search.createColumn(options)而query可以使用SELECT*FROM来动态返回所有的数据列(这在有的时候是一个优点),那么如......
  • BIKE test
    /******************************************************************************BIKE--BitFlippingKeyEncapsulationCopyright(c)2017NirDrucker,ShayGueron,RafaelMisoczki([email protected],[email protected],[email protected])......
  • 【java】【集合类】HashMap 与HashTable的区别
    1.继承的父类不同HashMap是继承自AbstractMap类,而HashTable是继承自Dictionary类。不过它们都实现了同时实现了map、Cloneable(可复制)、Serializable(可序列化)这三个接口HashMap继承、实现关系如下: HashTable继承、实现关系如下: Dictionary类是一个已经被废弃的类(见其源码......