yml配置org.springframework.boot spring-boot-starter-data-elasticsearch
# es 服务地址 elasticsearch.host=127.0.0.1 # es 服务端口 elasticsearch.port=9200Java配置类
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;
@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;
@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写个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笔记地址Elasticsearch7学习笔记(上) - 简书Elasticsearch7学习笔记(上)[https://www.jianshu.com/p/29e5b1a7ce61]Elasticsearch7学习笔记(中)[http...https://www.jianshu.com/p/29e5b1a7ce61
上一篇:介绍了es采用docker-compose的方式安装



