ElasticSearch helloWorld

837 阅读2分钟

1. docker安装ES

执行运行命令

docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:6.8.1

请求接口地址

GET 192.168.12.233:9200

{
    "name": "6kwfp3o",
    "cluster_name": "docker-cluster",
    "cluster_uuid": "GnJW9Mn_SlmKaCEdED0LdQ",
    "version": {
        "number": "6.7.2",
        "build_flavor": "default",
        "build_type": "docker",
        "build_hash": "56c6e48",
        "build_date": "2019-04-29T09:05:50.290371Z",
        "build_snapshot": false,
        "lucene_version": "7.7.0",
        "minimum_wire_compatibility_version": "5.6.0",
        "minimum_index_compatibility_version": "5.0.0"
    },
    "tagline": "You Know, for Search"
}

2. springboot集成ES

使用springboot版本2.1.6.RELEASE

引入相关依赖

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

yml配置

application.yml

# elasticsearch
spring:
  data:
    elasticsearch:
      # 集群名 与192.168.12.233:9200查询cluster_name保持一致,否则无法连接
      cluster-name: docker-cluster
      # 注意java的es默认连接端口是9300,9200是http端口,这两个在使用中应注意区分
      cluster-nodes: 192.168.12.233:9300

构建实体对象

Book.java

import java.io.Serializable;
import java.util.Date;

/**
 * ElasticSearch索引对象必须标注@Document注解,indexName为索引名,type为索引类型(PS:这是
 * ElasticSearch特性,同样的索引,可以分为不同的类型,来分别做索引)
 *
 * @author zhangbin
 * @date 2019/07/12
 */
@Data
@Document(indexName = "book", type = "it")
public class Book implements Serializable {
    /**
     * 坑一:这里的id主键必须为String类型,且必须加@Id注解,否则创建索引时,无法将主键转换成
     * 索引id,这样索引id就是null
     */
    @Id
    private String id;

    private String name;

    private Float price;

    private Date publishDate;
}

持久层

BookElasticsearchRepository.java

import com.zhangbin.es.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchPersistentEntity;
import org.springframework.data.elasticsearch.repository.support.AbstractElasticsearchRepository;
import org.springframework.data.elasticsearch.repository.support.ElasticsearchEntityInformation;
import org.springframework.data.elasticsearch.repository.support.MappingElasticsearchEntityInformation;
import org.springframework.data.util.ClassTypeInformation;
import org.springframework.data.util.TypeInformation;
import org.springframework.stereotype.Repository;

/**
 * BookElasticsearchRepository
 *
 * @author zhangbin
 * @date 2019/07/12
 */
@Repository("bookRepository")
public class BookElasticsearchRepository extends AbstractElasticsearchRepository<Book, String> {
    /**
     * 当AbstractElasticsearchRepository提供的方法不足以完成全部功能时,即可通过该对象自定义
     * 操作行为。
     */
    private ElasticsearchOperations elasticsearchOperations;

    /**
     * 注入ElasticsearchOperations,并实例化BookElasticsearchRepository
     * 这里注入ElasticsearchOperations对象就是在application.yml中配置的参数自动装载的对象
     * <p>
     * 坑二:必须super(createElasticsearchEntityInformation(), elasticsearchOperations),否则
     * 会报错
     */
    @Autowired
    public BookElasticsearchRepository(ElasticsearchOperations elasticsearchOperations) {
        super(createElasticsearchEntityInformation(), elasticsearchOperations);
        this.elasticsearchOperations = elasticsearchOperations;
    }

    /**
     * 创建ElasticsearchEntityInformation对象,该对象实现对索引对象相关信息的读取
     */
    private static ElasticsearchEntityInformation<Book, String> createElasticsearchEntityInformation() {
        TypeInformation<Book> typeInformation = ClassTypeInformation.from(Book.class);

        ElasticsearchPersistentEntity<Book> entity = new SimpleElasticsearchPersistentEntity<Book>(typeInformation);

        return new MappingElasticsearchEntityInformation<>(entity);
    }

    /**
     * id的展示方式
     *
     * @param aLong id
     */
    @Override
    protected String stringIdRepresentation(String aLong) {
        return aLong;
    }
}

测试接口

BookController.java

import com.zhangbin.es.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Optional;

/**
 * BookController
 *
 * @author zhangbin
 * @date 2019/07/12
 */
@RestController
public class BookController {

    @Autowired
    private PagingAndSortingRepository<Book, String> bookRepository;

    @GetMapping("/book/{id}")
    public Book getBookById(@PathVariable String id) {
        Optional<Book> bookOptional = bookRepository.findById(id);
        return bookOptional.orElse(null);
    }

    @PostMapping("/book")
    public Book addBook(@RequestBody Book book) {
        book.setPublishDate(new Date(System.currentTimeMillis()));
        return bookRepository.save(book);
    }
}

3. Postman测试

往es中添加数据

POST localhost:8888/book

requestBody

{
	"id":"20190712154609",
	"name":"prince and me",
	"price":12.23,
	"publishDate":1562917662000
}

responseBody

{
    "id": "20190712154609",
    "name": "prince and me",
    "price": 12.23,
    "publishDate": "2019-07-12T07:47:48.243+0000"
}

查询数据

GET localhost:8888/book/{id}

parthVariable

variable value
id 20190712154609

responseBody

{
    "id": "20190712154609",
    "name": "prince and me",
    "price": 12.23,
    "publishDate": "2019-07-12T07:47:48.243+0000"
}

源代码gitee地址