springboot整合ElasticSearch
-
-
<dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> </dependency> -
因为SpringBoot默认的ES版本是7.17.10,所以我们需要覆盖默认的ES版本:
<properties> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> <elasticsearch.version>7.12.1</elasticsearch.version> </properties> -
application
es: host: 192.168.43.135 port: 9200 -
EsProperties
@Data @Configuration @ConfigurationProperties(prefix = "es") public class EsProperties { private String host; private Integer port; } -
EsConfig
@Configuration public class EsConfig { @Autowired private EsProperties esProperties; @Bean public RestHighLevelClient restHighLevelClient() { return new RestHighLevelClient(RestClient.builder(new HttpHost(esProperties.getHost() , esProperties.getPort()))); } } -
创建数据库对应的索引库
查看代码
PUT /hotel { "mappings": { "properties": { "id": { "type": "keyword" }, "name":{ "type": "text", "analyzer": "ik_max_word", "copy_to": "all" }, "address":{ "type": "keyword", "index": false }, "price":{ "type": "integer" }, "score":{ "type": "integer" }, "brand":{ "type": "keyword", "copy_to": "all" }, "city":{ "type": "keyword", "copy_to": "all" }, "starName":{ "type": "keyword" }, "business":{ "type": "keyword" }, "location":{ "type": "geo_point" }, "pic":{ "type": "keyword", "index": false }, "all":{ "type": "text", "analyzer": "ik_max_word" }, "isAD":{ "type": "boolean" } } } } -
批量从数据库把数据导入到elasticsearch中
@SpringBootTest class HotelDemoApplicationTests { @Autowired private HotelService hotelService; @Autowired private RestHighLevelClient client; @Test void contextLoads() throws IOException { List<Hotel> list = hotelService.list(); BulkRequest bulkRequest = new BulkRequest(); List<HotelDoc> hotelDocs = BeanUtil.copyToList(list, HotelDoc.class); for (HotelDoc hotelDoc : hotelDocs) { bulkRequest.add(new IndexRequest("hotel") .id(hotelDoc.getId().toString()) .source(JSONUtil.toJsonStr(hotelDoc), XContentType.JSON) ); } client.bulk(bulkRequest, RequestOptions.DEFAULT); } } - 写controller……service
-

浙公网安备 33010602011771号