Elasticsearch 基于项目的使用

版权声明:望支持~~~ https://blog.csdn.net/u011663149/article/details/86623363

前言:

     Elasticsearch 是一个分布式可扩展的实时搜索和分析引擎,一个建立在全文搜索引擎 Apache Lucene(TM) 基础上的搜索引擎.当然 Elasticsearch 并不仅仅是 Lucene 那么简单,它不仅包括了全文搜索功能,还可以进行以下工作:

  • 分布式实时文件存储,并将每一个字段都编入索引,使其可以被搜索。
  • 实时分析的分布式搜索引擎。
  • 可以扩展到上百台服务器,处理PB级别的结构化或非结构化数据。

其实它的文件存储跟mongodb一样是面向文档型数据库(JSON作为文档序列化的格式)。

下载安装地址: https://www.elastic.co/cn/downloads/past-releases/elasticsearch-6-4-3 具体安装很简单不做介绍。

如何进行项目的集成和使用:

1.基于springboot项目添加pom:

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

2.yml配置es的服务地址:

spring:
   data:
        elasticsearch: 
            cluster-name: #默认为elasticsearch
            cluster-nodes:127.0.0.1:9300 #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode
            properties:
                path:
                  logs: ./elasticsearch/log #elasticsearch日志存储目录
                  data: ./elasticsearch/data #elasticsearch数据存储目录

3.创建一个Test的文档类:

@Data
@Document(indexName = "test", type = "test", shards = 1, replicas = 0, refreshInterval = "-1")
public class Test {

	@Id
	private String id;

	private String firstName;

	private String lastName;

}	 

还是同样参考mongo,创建索引之类的。

4.创建Repository:

public interface CustomerRepository extends ElasticsearchRepository<Test, String> {

	Test findByFirstName(String firstName);

	List<Test> findByLastName(String lastName);

}

5.测试:

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

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private CustomerRepository repository;

    @RequestMapping("/indexExists/{indexName}")
    public Boolean indexExists(@PathVariable String indexName) {
        return elasticsearchTemplate.indexExists(indexName);
    }

    @RequestMapping("/save")
    public String testEsRepo() {
        saveCustomers();
        return "OK";
    }

    @RequestMapping("/fetchAll")
    public Iterable<Test> fetchAll() {
        return this.repository.findAll();
    }

    @RequestMapping("/findByFirstName")
    public Test findByFirstName() {
        return this.repository.findByFirstName("Alice");
    }

    @RequestMapping("/findByLastName")
    public List<Test> findByLastName() {
        return this.repository.findByLastName("Smith");
    }

    private void saveCustomers() {
        this.repository.deleteAll();
        this.repository.save(new Test("Alice", "Smith"));
        this.repository.save(new Test("Bob", "Smith"));
    }

对于ES的复合查询之后进行优化~望支持


猜你喜欢

转载自blog.csdn.net/u011663149/article/details/86623363