搜索功能,如果直接使用MySQL的like查询语句会影响系统的性能,所以使用es会显著的提升性能呢。

创建spriingboot项目,在非关系型数据库中选中es,就会自动导入es的maven相关的包啦。

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

springboot的版本不要选太高,不然es对应的版本也会高的,需要和自己的es版本相对应。

需要建立一个bean类进行注入

/**
 * ElasticSearch 客户端配置
 */
@Configuration
public class RestClientConfig extends AbstractElasticsearchConfiguration {
    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo("localhost:9200")
                .build();
        return RestClients.create(clientConfiguration).rest();
    }
}

也可以在yml中进行配置

server:
  port: 10068
spring:
  application:
    name: search
  data:
    elasticsearch:
      cluster-name: my-application
      cluster-nodes: 192.168.10.12:9300 #es安装的节点

官方使用示例

@RestController
@RequestMapping("/")
public class TestController {

  private  ElasticsearchOperations elasticsearchOperations;

  public TestController(ElasticsearchOperations elasticsearchOperations) { 
    this.elasticsearchOperations = elasticsearchOperations;
  }

  @PostMapping("/person")
  public String save(@RequestBody Person person) {                         

    IndexQuery indexQuery = new IndexQueryBuilder()
      .withId(person.getId().toString())
      .withObject(person)
      .build();
    String documentId = elasticsearchOperations.index(indexQuery);
    return documentId;
  }

  @GetMapping("/person/{id}")
  public Person findById(@PathVariable("id")  Long id) {                   
    Person person = elasticsearchOperations
      .queryForObject(GetQuery.getById(id.toString()), Person.class);
    return person;
  }
}
1让 Spring 注入提供的 ElasticsearchOperations构造函数中的bean。
2在 Elasticsearch 集群中存储一些实体。
3通过 id 检索具有查询的实体。

 官方文档有许多资料:Spring Data Elasticsearch - Reference Documentationicon-default.png?t=M1H3https://docs.spring.io/spring-data/elasticsearch/docs/4.1.2/reference/html/#preface

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐