美高梅网投网站-美高梅手机网投-美高梅官方网站
做最好的网站

您的位置:美高梅网投网址 > 美高梅网站 > Boot 2.0.5默认的elasticsearch版本很低

Boot 2.0.5默认的elasticsearch版本很低

发布时间:2019-09-29 06:16编辑:美高梅网站浏览(200)

    1. 前言

    介绍

    笔录将elasticsearch集成到spring boot的进度,以及部分简短的行使和helper类使用。

    1.1. 集成情势

    紧接格局

    使用spring-boot中的spring-data-elasticsearch,能够动用三种内置客商端连着

    • 节点客商端(node client):
      铺排文件中装置为local:false,节点顾客端以重重据节点(node-master或node-client)身份参与集群,换言之,它和煦不存储任何数据,不过它知道多少在集群中的具体地方,並且能够直接转接呼吁到对应的节点上。
    • 传输客商端(Transport client):
      布置文件中设置为local:true,那么些更轻量的传输顾客端可以发送央浼到长途集群。它自身不参预集群,只是简短转载呼吁给集群中的节点。

    几个Java客户端都经过9300端口与集群交互,使用Elasticsearch传输公约(Elasticsearch Transport Protocol)。集群中的节点之间也经过9300端口举行通讯。假诺此端口未开放,你的节点将不能够构成集群。

    Spring Boot中集成Elasticsearch有4种方式:

    环境

    1. REST Client
    2. Jest
    3. Spring Data
    4. Spring Data Elasticsearch Repositories

    本子包容

    请一定留心版本宽容难点。那提到到相当多maven信赖。Spring Data Elasticsearch Spring Boot version matrix

    美高梅网投网站 1

    本子包容列表.png

    本文用前面三种办法来分别连接并操作Elasticsearch

    搭建处境

    Spring boot: 1.4.1.RELEASE
    spring-data-elasticsearch: 用了最基础的spring-boot-starter-data-elasticsearch,选用高版本时供给对此增进es服务版本
    elasticsearch: 2.3.0

    1.2. 意况与配置

    Maven依赖

    <parent>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-parent</artifactId>
          <version>1.4.1.RELEASE</version>
          <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
     </dependency>
    

    服务端:elasticsearch-6.3.2 1台

    布署文件

    bootstrap.yml

    spring:
      data:
        elasticsearch:
          # 集群名
          cluster-name: syncwt-es
          # 连接节点,注意在集群中通信都是9300端口,否则会报错无法连接上!
          cluster-nodes: localhost:9300,119.29.38.169:9300
          # 是否本地连接
          local: false
          repositories:
            # 仓库中数据存储
            enabled: true
    

    客户端:elasticsearch 6.4.1

    美高梅网投网站,调试

    服务端配置文件:elasticsearch.yml

    启动

    开发银行项目,日志现身以下表明表示成功。而且未有报错。

     2017-03-30 19:35:23.078  INFO 20881 --- [           main] o.s.d.e.c.TransportClientFactoryBean     : adding transport node : localhost:9300
    
    cluster.name: my-applicationnetwork.host: 192.168.1.134http.port: 9200
    

    知识点

    在Elasticsearch中,文书档案归属于一种等级次序(type),而那些品种存在于索引(index)中,大家得以画一些差相当少的相比较图来类比守旧关系型数据库:
    Elasticsearch集群能够包罗四个目录(indices)(数据库),每叁个目录能够分包多少个系列(types)(表),每多少个体系蕴涵多个文书档案(documents)(行),然后每种文书档案满含三个字段(菲尔德s)(列)

    Relational DB -> Databases -> Tables -> Rows -> Columns
    Elasticsearch -> Indices   -> Types  -> Documents -> Fields
    

    美高梅手机网投,/etc/security/limits.conf

    Demo

    Customer.java

    /*
     * Copyright 2012-2013 the original author or authors.
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *      http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    package com.syncwt.www.common.es;
    
    import org.springframework.data.annotation.Id;
    import org.springframework.data.elasticsearch.annotations.Document;
    
    @Document(indexName = "es-customer", type = "customer", shards = 2, replicas = 1, refreshInterval = "-1")
    public class Customer {
    
        @Id
        private String id;
    
        private String firstName;
    
        private String lastName;
    
        public Customer() {
        }
    
        public Customer(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }
    
        public String getId() {
            return this.id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public String getFirstName() {
            return this.firstName;
        }
    
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }
    
        public String getLastName() {
            return this.lastName;
        }
    
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
    
        @Override
        public String toString() {
            return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id,
                    this.firstName, this.lastName);
        }
    
    }
    

    CustomerRepository.java

    /*
     * Copyright 2012-2013 the original author or authors.
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *      http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    package com.syncwt.www.common.es;
    
    import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
    
    import java.util.List;
    
    public interface CustomerRepository extends ElasticsearchRepository<Customer, String> {
    
        public List<Customer> findByFirstName(String firstName);
    
        public List<Customer> findByLastName(String lastName);
    
    }
    

    CustomerController.java

    package com.syncwt.www.web;
    
    import com.syncwt.www.response.Message;
    import com.syncwt.www.service.CustomerService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.io.IOException;
    
    /**
     * @version v0.0.1
     * @Description CustomerController
     * @Author wanwt@senthink.com
     * @Creation Date 2017年03月30日 下午8:21
     * @ModificationHistory Who        When          What
     * --------   ----------    -----------------------------------
     */
    @RestController
    public class CustomerController {
        @Autowired
        private CustomerService customerService;
    
    
        @RequestMapping(value = "/test", method = RequestMethod.GET)
        public Message test() throws IOException {
            customerService.saveCustomers();
            customerService.fetchAllCustomers();
            customerService.fetchIndividualCustomers();
            return Message.SUCCESS;
        }
    }
    

    CustomerService.java

    package com.syncwt.www.service;
    
    import com.syncwt.www.common.es.Customer;
    import com.syncwt.www.common.es.CustomerRepository;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.io.IOException;
    
    /**
     * @version v0.0.1
     * @Description 业务层
     * @Author wanwt@senthink.com
     * @Creation Date 2017年03月30日 下午8:19
     * @ModificationHistory Who        When          What
     * --------   ----------    -----------------------------------
     */
    @Service
    public class CustomerService {
    
        @Autowired
        private CustomerRepository repository;
    
        public void saveCustomers() throws IOException {
            repository.save(new Customer("Alice", "Smith"));
            repository.save(new Customer("Bob", "Smith"));
        }
    
        public void fetchAllCustomers() throws IOException {
            System.out.println("Customers found with findAll():");
            System.out.println("-------------------------------");
            for (Customer customer : repository.findAll()) {
                System.out.println(customer);
            }
        }
    
        public void fetchIndividualCustomers() {
            System.out.println("Customer found with findByFirstName('Alice'):");
            System.out.println("--------------------------------");
            System.out.println(repository.findByFirstName("Alice"));
    
            System.out.println("Customers found with findByLastName('Smith'):");
            System.out.println("--------------------------------");
            for (Customer customer : repository.findByLastName("Smith")) {
                System.out.println(customer);
            }
        }
    }
    
    cheng soft nofile 65536cheng hard nofile 65536
    

    spring对es的操作方法

    /etc/sysctl.conf

    spring-data-elasticsearch查询情势的卷入

    1. 装进数据库基本CRUD(创立(Create)、更新(Update)、读取(Retrieve)和删除(Delete))
    public interface CrudRepository<T, ID extends Serializable>
        extends Repository<T, ID> {
    
        <S extends T> S save(S entity);
    
        T findOne(ID primaryKey);       
    
        Iterable<T> findAll();          
    
        Long count();                   
    
        void delete(T entity);          
    
        boolean exists(ID primaryKey);  
    
        // … more functionality omitted.
    }
    
    1. 分页排序查询
    public interface PagingAndSortingRepository<T, ID extends Serializable>
      extends CrudRepository<T, ID> {
    
      Iterable<T> findAll(Sort sort);
    
      Page<T> findAll(Pageable pageable);
    }
    
    //Accessing the second page by a page size of 20
    PagingAndSortingRepository<User, Long> repository = // … get access to a bean
    Page<User> users = repository.findAll(new PageRequest(1, 20));
    
    1. 计数
    public interface UserRepository extends CrudRepository<User, Long> {
    
      Long countByLastname(String lastname);
    }
    
    1. 删除
    public interface UserRepository extends CrudRepository<User, Long> {
    
      Long deleteByLastname(String lastname);
    
      List<User> removeByLastname(String lastname);
    
    }
    
    1. 自定义查询艺术自动注入
    • 宣称贰个接口继承Repository<T, ID>
    interface PersonRepository extends Repository<Person, Long> { … }
    
    • 接口中自定义方法,在格局名中包罗T中字段名
      查询关键字归纳find…By, read…By, query…By, count…By, and get…By,熟识直接能够用And and Or连接
      interface PersonRepository extends Repository<Person, Long> {
       List<Person> findByLastname(String lastname);
     }
    
    • 管教注入了elasticsearch配置
      bootstrap.yml中写入了spring-data-elasticsearch的配备文件将自行注入
    • 流入调用
    public class SomeClient {
    
      @Autowired
      private PersonRepository repository;
    
      public void doSomething() {
        List<Person> persons = repository.findByLastname("Matthews");
      }
    }
    
    1. 支撑Java8 Stream查询和sql语句询问
    @Query("select u from User u")
    Stream<User> findAllByCustomQueryAndStream();
    
    Stream<User> readAllByFirstnameNotNull();
    
    @Query("select u from User u")
    Stream<User> streamAllPaged(Pageable pageable);
    
    try (Stream<User> stream = repository.findAllByCustomQueryAndStream()) {
      stream.forEach(…);
    }
    
    1. 援助异步查询
    @Async
    Future<User> findByFirstname(String firstname);               
    
    @Async
    CompletableFuture<User> findOneByFirstname(String firstname);
    
    @Async
    ListenableFuture<User> findOneByLastname(String lastname);
    
    vm.max_map_count=262144
    

    美高梅官方网站,支撑原生es JavaAPI

    1. NativeSearchQueryBuilder创设查询
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    
    SearchQuery searchQuery = new NativeSearchQueryBuilder()
        .withQuery(matchAllQuery())
        .withFilter(boolFilter().must(termFilter("id", documentId)))
        .build();
    
    Page<SampleEntity> sampleEntities =
        elasticsearchTemplate.queryForPage(searchQuery,SampleEntity.class);
    
    1. 利用ScanScroll扩充大结果集查询
    SearchQuery searchQuery = new NativeSearchQueryBuilder()
        .withQuery(matchAllQuery())
        .withIndices("test-index")
        .withTypes("test-type")
        .withPageable(new PageRequest(0,1))
        .build();
    String scrollId = elasticsearchTemplate.scan(searchQuery,1000,false);
    List<SampleEntity> sampleEntities = new ArrayList<SampleEntity>();
    boolean hasRecords = true;
    while (hasRecords){
        Page<SampleEntity> page = elasticsearchTemplate.scroll(scrollId, 5000L , new ResultsMapper<SampleEntity>()
        {
            @Override
            public Page<SampleEntity> mapResults(SearchResponse response) {
                List<SampleEntity> chunk = new ArrayList<SampleEntity>();
                for(SearchHit searchHit : response.getHits()){
                    if(response.getHits().getHits().length <= 0) {
                        return null;
                    }
                    SampleEntity user = new SampleEntity();
                    user.setId(searchHit.getId());
                    user.setMessage((String)searchHit.getSource().get("message"));
                    chunk.add(user);
                }
                return new PageImpl<SampleEntity>(chunk);
            }
        });
        if(page != null) {
            sampleEntities.addAll(page.getContent());
            hasRecords = page.hasNextPage();
        }
        else{
            hasRecords = false;
        }
        }
    }
    
    1. 收获client实例举办节点操作,能够自行封装Util方法
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    
    public void searchHelper() throws IOException {
    
            //节点客户端
            // on startup
    //        Node node = nodeBuilder().clusterName("syncwt-es").client(true).node();
    //        Client nodeClient = node.client();
    
            //传输客户端
    //        Settings settings = Settings.settingsBuilder().build();
    //        Client transportClient = TransportClient.builder().settings(settings).build();
    
            Client transportClient = elasticsearchTemplate.getClient();
    
            Customer customer = new Customer("Alice", "Smith");
    
            // instance a json mapper
            ObjectMapper mapper = new ObjectMapper(); // create once, reuse
    
            // generate json
            String json = mapper.writeValueAsString(customer);
            System.out.println("--------------------------------jackson mapper");
            System.out.println(json);
    
            XContentBuilder builder = jsonBuilder()
                    .startObject()
                    .field("firstName", "Alice")
                    .field("latName", "Smith")
                    .endObject();
            System.out.println("--------------------------------jsonBuilder");
            System.out.println(builder.string());
    
            IndexResponse response = transportClient.prepareIndex("es-customer", "customer")
                    .setSource(jsonBuilder()
                            .startObject()
                            .field("firstName", "Alice")
                            .field("latName", "Smith")
                            .endObject()
                    )
                    .execute()
                    .actionGet();
    
            System.out.println("--------------------------------response");
            System.out.println(response.toString());
    
            // on shutdown
    //        node.close();
    //        nodeClient.close();
            transportClient.close();
    
        }
    

    1.3. 版本

    总结

    1. spring-data-elasticsearch对es有很好的援救,但众多高版本在spring-boot中不是很投机。所以,除了spring-boot自动配置的章程,最棒精通代码动态配置方式。
    2. 为了操作的便利性,大家往往需要动态索引,因为同三个目录(固定)是无法知足集群中多事情的。所以持续封装三个EsUtil类作为着力操作公共交通类

    Spring Boot 2.0.5私下认可的elasticsearch版本相当的低,这里咱们用时髦版本6.4.1

    参考

    Spring Data ElasticSearch
    Spring Data Elasticsearch介绍
    elasticsearch华语指南
    Spring Data Elasticsearch

    设若开发银行进程中冒出

    java.lang.NoClassDefFoundError: org/elasticsearch/common/transport/InetSocketTransportAddress
    

    则印证,elasticsearch依赖的jar包版本不平等,统一改成6.4.1即可

    除此以外,Spring Boot 2.0.5信赖的spring-data-elasticsearch版本是3.0.1,必要升高到3.1.0

    美高梅网投网站 2

    2. 依赖

    <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>com.cjs.example</groupId>    <artifactId>cjs-elasticsearch-example</artifactId>    <version>0.0.1-SNAPSHOT</version>    <packaging>jar</packaging>    <name>cjs-elasticsearch-example</name>    <description></description>    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>2.0.5.RELEASE</version>        <relativePath/> <!-- lookup parent from repository -->    </parent>    <properties>        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>        <java.version>1.8</java.version>        <elasticsearch.version>6.4.1</elasticsearch.version>        <spring.data.elasticsearch.version>3.1.0.RELEASE</spring.data.elasticsearch.version>    </properties>    <dependencies>        <dependency>            <groupId>org.elasticsearch</groupId>            <artifactId>elasticsearch</artifactId>            <version>${elasticsearch.version}</version>        </dependency>        <dependency>            <groupId>org.elasticsearch.client</groupId>            <artifactId>transport</artifactId>            <version>${elasticsearch.version}</version>        </dependency>        <dependency>            <groupId>org.elasticsearch.client</groupId>            <artifactId>elasticsearch-rest-client</artifactId>            <version>${elasticsearch.version}</version>        </dependency>        <dependency>            <groupId>org.elasticsearch.plugin</groupId>            <artifactId>transport-netty4-client</artifactId>            <version>${elasticsearch.version}</version>        </dependency>        <dependency>            <groupId>org.springframework.data</groupId>            <artifactId>spring-data-elasticsearch</artifactId>            <version>${spring.data.elasticsearch.version}</version>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>        <dependency>            <groupId>org.projectlombok</groupId>            <artifactId>lombok</artifactId>            <optional>true</optional>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency>    </dependencies>    <build>        <plugins>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>            </plugin>        </plugins>    </build></project>
    

    3. application.properties

    spring.data.elasticsearch.cluster-name=my-applicationspring.data.elasticsearch.cluster-nodes=192.168.1.134:9300
    

    或然,大家会疑忌,配置文件中明显写的端口是9200,为什么这里配置文件中总是的时候写的端口是9300吗?

    因为,配置9200是由此HTTP连接的端口,9300是TCP连接的端口

    美高梅网投网站 3

    4. 操作

    4.1. 使用Spring Data Elasticsearch Repositories操作Elasticsearch

    率先,定义三个实体类

    package com.cjs.example.entity;import lombok.Data;import org.springframework.data.annotation.Id;import org.springframework.data.elasticsearch.annotations.Document;import java.io.Serializable;@Data@Document(indexName = "commodity")public class Commodity implements Serializable {    @Id    private String skuId;    private String name;    private String category;    private Integer price;    private String brand;    private Integer stock;}
    

    此处定义了Commodity实例,表示商品。在Elasticsearch 6.X 版本中,不提出选用type,并且在7.X版本中将会通透到底丢掉type,所以这里小编只钦命了indexName,没有一点点名type。这里,三个Commodity代表三个货色,同一时间意味着一条索引记录。

    类比关系型数据库的话,Index也正是表,Document也等于记录

    下一场,须求团结定义五个接口,并承袭ElasticsearchRepository

    美高梅网投网站 4

    package com.cjs.example.dao;import com.cjs.example.entity.Commodity;import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;import org.springframework.stereotype.Repository;@Repositorypublic interface CommodityRepository extends ElasticsearchRepository<Commodity, String> {}
    

    此间的Repository相当于DAO,操作mysql依然elasticsearch没什么差别的

    接下来,定义service接口

    package com.cjs.example.service;import com.cjs.example.entity.Commodity;import org.springframework.data.domain.Page;import java.util.List;public interface CommodityService {    long count();    Commodity save(Commodity commodity);    void delete(Commodity commodity);    Iterable<Commodity> getAll();    List<Commodity> getByName(String name);    Page<Commodity> pageQuery(Integer pageNo, Integer pageSize, String kw);}
    

    实现类

    package com.cjs.example.service.impl;import com.cjs.example.entity.Commodity;import com.cjs.example.dao.CommodityRepository;import com.cjs.example.service.CommodityService;import org.elasticsearch.index.query.MatchQueryBuilder;import org.elasticsearch.index.query.QueryBuilders;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.domain.Page;import org.springframework.data.domain.PageRequest;import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;import org.springframework.data.elasticsearch.core.query.SearchQuery;import org.springframework.stereotype.Service;import java.util.ArrayList;import java.util.List;@Servicepublic class CommodityServiceImpl implements CommodityService {    @Autowired    private CommodityRepository commodityRepository;    @Override    public long count() {        return commodityRepository.count();    }    @Override    public Commodity save(Commodity commodity) {        return commodityRepository.save(commodity);    }    @Override    public void delete(Commodity commodity) {        commodityRepository.delete(commodity);//        commodityRepository.deleteById(commodity.getSkuId;    }    @Override    public Iterable<Commodity> getAll() {        return commodityRepository.findAll();    }    @Override    public List<Commodity> getByName(String name) {        List<Commodity> list = new ArrayList<>();        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("name", name);        Iterable<Commodity> iterable = commodityRepository.search(matchQueryBuilder);        iterable.forEach(e->list.add;        return list;    }    @Override    public Page<Commodity> pageQuery(Integer pageNo, Integer pageSize, String kw) {        SearchQuery searchQuery = new NativeSearchQueryBuilder()                .withQuery(QueryBuilders.matchPhraseQuery("name", kw))                .withPageable(PageRequest.of(pageNo, pageSize))                .build();        return commodityRepository.search(searchQuery);    }}
    

    在这几个Service中示范了增加和删除查改操作,还应该有分页查询

    末段,写二个测验类测量检验之中的点子

    package com.cjs.example;import com.cjs.example.entity.Commodity;import com.cjs.example.service.CommodityService;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.data.domain.Page;import org.springframework.test.context.junit4.SpringRunner;import java.util.List;@RunWith(SpringRunner.class)@SpringBootTestpublic class CjsElasticsearchExampleApplicationTests {    @Autowired    private CommodityService commodityService;    @Test    public void contextLoads() {        System.out.println(commodityService.count;    }    @Test    public void testInsert() {        Commodity commodity = new Commodity();        commodity.setSkuId("1501009001");        commodity.setName("原味切片面包");        commodity.setCategory("101");        commodity.setPrice(880);        commodity.setBrand("良品铺子");        commodityService.save(commodity);        commodity = new Commodity();        commodity.setSkuId("1501009002");        commodity.setName("原味切片面包");        commodity.setCategory("101");        commodity.setPrice(680);        commodity.setBrand("良品铺子");        commodityService.save(commodity);        commodity = new Commodity();        commodity.setSkuId("1501009004");        commodity.setName("元气吐司850g");        commodity.setCategory("101");        commodity.setPrice(120);        commodity.setBrand("百草味");        commodityService.save(commodity);    }    @Test    public void testDelete() {        Commodity commodity = new Commodity();        commodity.setSkuId("1501009002");        commodityService.delete(commodity);    }    @Test    public void testGetAll() {        Iterable<Commodity> iterable = commodityService.getAll();        iterable.forEach(e->System.out.println(e.toString;    }    @Test    public void testGetByName() {        List<Commodity> list = commodityService.getByName("面包");        System.out.println;    }    @Test    public void testPage() {        Page<Commodity> page = commodityService.pageQuery(0, 10, "切片");        System.out.println(page.getTotalPages;        System.out.println(page.getNumber;        System.out.println(page.getContent;    }}
    

    如上,正是利用Elasticsearch Repositories的法门

    4.2. 选用ElasticsearchTemplate形式操作Elasticsearch

    package com.cjs.example;import com.cjs.example.entity.Commodity;import org.elasticsearch.index.query.QueryBuilders;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;import org.springframework.data.elasticsearch.core.query.*;import org.springframework.test.context.junit4.SpringRunner;import java.util.List;@RunWith(SpringRunner.class)@SpringBootTestpublic class ElasticsearchTemplateTest {    @Autowired    public ElasticsearchTemplate elasticsearchTemplate;    @Test    public void testInsert() {        Commodity commodity = new Commodity();        commodity.setSkuId("1501009005");        commodity.setName("葡萄吐司面包");        commodity.setCategory("101");        commodity.setPrice(160);        commodity.setBrand("良品铺子");        IndexQuery indexQuery = new IndexQueryBuilder().withObject(commodity).build();        elasticsearchTemplate.index(indexQuery);    }    @Test    public void testQuery() {        SearchQuery searchQuery = new NativeSearchQueryBuilder()                .withQuery(QueryBuilders.matchQuery("name", "吐司"))                .build();        List<Commodity> list = elasticsearchTemplate.queryForList(searchQuery, Commodity.class);        System.out.println;    }}
    

    ElasticsearchTemplate是全自动配置的

    美高梅网投网站 5

    1. 演示

    美高梅网投网站 6

    美高梅网投网站 7

    1. 工程协会

    美高梅网投网站 8

    1. 参考

    本文由美高梅网投网址发布于美高梅网站,转载请注明出处:Boot 2.0.5默认的elasticsearch版本很低

    关键词:

上一篇:c) 一个指向指针的的指针

下一篇:没有了