maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
yml配置
# es 服务地址
elasticsearch.host=127.0.0.1
# es 服务端口
elasticsearch.port=9200
Java配置类
import lombok.Data;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
/**
* @Author Eric
* @Date 2021/7/27 10:40
* @Version 1.0
*/
@ConfigurationProperties(prefix = "elasticsearch")
@Configuration
@Data
public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {
private String host;
private Integer port;
@Override
public RestHighLevelClient elasticsearchClient() {
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));
RestHighLevelClient restHighLevelClient = new
RestHighLevelClient(builder);
return restHighLevelClient;
}
}
实体类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* @Author Eric
* @Date 2021/7/27 10:37
* @Version 1.0
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Document(indexName = "product",shards = 3,replicas = 1)//shards主分片replicas副本
public class Product {
@Id()
private Long id;//商品唯一标识
@Field(type = FieldType.Text,analyzer = "ik_max_word")
private String title;//商品名称
@Field(type = FieldType.Keyword)
private String category;//分类名称
@Field(type = FieldType.Double)
private Double price;//商品价格
@Field(type = FieldType.Keyword,index = false)
private String images;//图片地址
}
Dao
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface ProductDao extends ElasticsearchRepository<Product,Long> {
}
写个controller
类似下面代码。项目启动时索引会自动创建
public R<?> es(@RequestBody VO request) {
log.info("######参数是{}", JSON.toJSONString(request));
Product product = new Product();
// product.setId(3L);
product.setTitle("华为手机");
product.setCategory("手机");
product.setPrice(2999.00);
product.setImages("http://www.gh.com");
return R.ok(productDao.save(product));
}
采用ik分词,类型text支持分词
spring官网配置elasticsearch
Spring Data Elasticsearch - Reference Documentation
其他ES笔记地址
上一篇:介绍了es采用docker-compose的方式安装