SpringBoot整合mongodb
實(shí)現(xiàn)步驟:
-
pom文件導(dǎo)坐標(biāo)
<!--mongo--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
-
yaml配置文件配置mongodb:
spring: data: mongodb: uri: mongodb://localhost/spring
-
隨便建一個(gè)pojo
@Data @NoArgsConstructor @AllArgsConstructor public class Book { private int id; private String name; private String type; private String description; }
-
測(cè)試:
@SpringBootTest class SpringbootMongodb01ApplicationTests { @Autowired(required = false) private MongoTemplate mongoTemplate; @Test void contextLoads() { Book book = new Book(); book.setId(4); book.setName("張三"); book.setType("牛逼"); book.setDescription("真牛逼"); mongoTemplate.save(book); } @Test void find(){ List<Book> all = mongoTemplate.findAll(Book.class); System.out.println(all); } }
裝配MongoTemplate模板類(lèi),調(diào)用方法
整合MongoDB總結(jié):
- 導(dǎo)坐標(biāo)
- 寫(xiě)配置文件
- 核心類(lèi)MongoTemplate調(diào)用
SpringBoot整合ElasticSearch
前提準(zhǔn)備:數(shù)據(jù)庫(kù)+ES
數(shù)據(jù)庫(kù)建表語(yǔ)句:
DROP TABLE IF EXISTS `tb_hotel`;
CREATE TABLE `tb_hotel` (
`id` bigint(20) NOT NULL COMMENT '酒店id',
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '酒店名稱(chēng)',
`address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '酒店地址',
`price` int(10) NOT NULL COMMENT '酒店價(jià)格',
`score` int(2) NOT NULL COMMENT '酒店評(píng)分',
`brand` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '酒店品牌',
`city` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '所在城市',
`star_name` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '酒店星級(jí),1星到5星,1鉆到5鉆',
`business` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商圈',
`latitude` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '緯度',
`longitude` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '經(jīng)度',
`pic` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '酒店圖片',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Compact;
實(shí)現(xiàn)步驟:
-
pom文件到坐標(biāo)
<properties> <!--鎖定jdk版本--> <java.version>1.8</java.version> <!--鎖定es版本--> <elasticsearch.version>7.12.0</elasticsearch.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.29</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <!--FastJson--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.71</version> </dependency> </dependencies>
-
yaml配置文件
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/spring?serverTimezone=GMT username: root password: 123456 logging: level: com.dong: debug mybatis-plus: configuration: map-underscore-to-camel-case: true type-aliases-package: com.dong.pojo
-
創(chuàng)建實(shí)體類(lèi):
對(duì)應(yīng)數(shù)據(jù)庫(kù)表的實(shí)體類(lèi)
@NoArgsConstructor @AllArgsConstructor @Data @TableName("tb_hotel") public class Hotel { @TableId(type = IdType.INPUT) private Long id; private String name; private String address; private Integer price; private Integer score; private String brand; private String city; private String starName; private String business; private String longitude;//經(jīng)度 private String latitude;//緯度 private String pic; }
對(duì)應(yīng)ES的實(shí)體類(lèi)
@Data @NoArgsConstructor public class HotelDoc { private Long id; private String name; private String address; private Integer price; private Integer score; private String brand; private String city; private String starName; private String business; private String location; private String pic; // 構(gòu)造方法用于類(lèi)型轉(zhuǎn)換 將數(shù)據(jù)庫(kù)中的經(jīng)、緯度用坐標(biāo)location代替,所以HotelDoc稍有不同 public HotelDoc(Hotel hotel){ this.id = hotel.getId(); this.name = hotel.getName(); this.address = hotel.getAddress(); this.price = hotel.getPrice(); this.score = hotel.getScore(); this.brand = hotel.getBrand(); this.city = hotel.getCity(); this.starName = hotel.getStarName(); this.business = hotel.getBusiness(); this.location = hotel.getLatitude() + ", "+ hotel.getLongitude(); this.pic = hotel.getPic(); } }
-
mapper層:
@Mapper public interface HotelMapper extends BaseMapper<Hotel> { }
-
service層:
接口:
public interface IHotelService extends IService<Hotel> { }
實(shí)現(xiàn)類(lèi):
@Service public class HotelServiceImp extends ServiceImpl<HotelMapper, Hotel> implements IHotelService { }
-
演示在juint中進(jìn)行,演示對(duì)索引庫(kù)和文檔的操作
索引庫(kù)的操作
- 判斷索引庫(kù)是否存在(其實(shí)就是查詢(xún))
- 創(chuàng)建索引庫(kù)
- 刪除索引庫(kù)
@SpringBootTest
class SpringbootEs01ApplicationTests {
// 操作es的核心對(duì)象
private RestHighLevelClient client;
// 單元測(cè)試之前都執(zhí)行的,告訴核心對(duì)象es的端口號(hào) 固定語(yǔ)法
@BeforeEach
void setUp(){
this.client = new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://localhost:9200")
));
}
// 單元測(cè)試之后都執(zhí)行的
@AfterEach
void tearDown() throws Exception{
this.client.close();
}
// 判斷索引庫(kù)是否存在
@Test
void testExistsHotelIndex() throws Exception {
GetIndexRequest request = new GetIndexRequest("hotels");
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
System.err.println(exists ? "索引庫(kù)已經(jīng)存在":"索引庫(kù)不存在");
}
// 創(chuàng)建索引庫(kù)
@Test
void createHotelIndex() throws Exception{
// 創(chuàng)建Request對(duì)象
CreateIndexRequest request = new CreateIndexRequest("hotels");
// 準(zhǔn)備請(qǐng)求的參數(shù):DSL語(yǔ)句
request.source(HotelConstants.MAPPING_TEMPLATE, XContentType.JSON);
// 發(fā)送請(qǐng)求
client.indices().create(request,RequestOptions.DEFAULT);
}
// 刪除索引庫(kù)
@Test
void delteHotelIndex() throws Exception{
// 創(chuàng)建Request對(duì)象
DeleteIndexRequest request = new DeleteIndexRequest("hotels");
// 發(fā)送請(qǐng)求
client.indices().delete(request,RequestOptions.DEFAULT);
}
}
創(chuàng)建索引庫(kù)的時(shí)候需要映射,映射往往是一個(gè)復(fù)雜且長(zhǎng)的JSON,所以單獨(dú)寫(xiě)個(gè)類(lèi),上面創(chuàng)建索引庫(kù)的映射如下
可以在postman中寫(xiě)好粘貼過(guò)來(lái)
public class HotelConstants {
public static final String MAPPING_TEMPLATE = "{\n" +
" \"mappings\": {\n" +
" \"properties\": {\n" +
" \"id\": {\n" +
" \"type\": \"keyword\"\n" +
" },\n" +
" \"name\":{\n" +
" \"type\": \"text\",\n" +
" \"analyzer\": \"ik_max_word\",\n" +
" \"copy_to\": \"all\"\n" +
" },\n" +
" \"address\":{\n" +
" \"type\": \"keyword\",\n" +
" \"index\": false\n" +
" },\n" +
" \"price\":{\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" \"score\":{\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" \"brand\":{\n" +
" \"type\": \"keyword\",\n" +
" \"copy_to\": \"all\"\n" +
" },\n" +
" \"city\":{\n" +
" \"type\": \"keyword\",\n" +
" \"copy_to\": \"all\"\n" +
" },\n" +
" \"starName\":{\n" +
" \"type\": \"keyword\"\n" +
" },\n" +
" \"business\":{\n" +
" \"type\": \"keyword\"\n" +
" },\n" +
" \"location\":{\n" +
" \"type\": \"geo_point\"\n" +
" },\n" +
" \"pic\":{\n" +
" \"type\": \"keyword\",\n" +
" \"index\": false\n" +
" },\n" +
" \"all\":{\n" +
" \"type\": \"text\",\n" +
" \"analyzer\": \"ik_max_word\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
}
文檔的操作
@SpringBootTest
public class HotelDocumentTests {
// 核心對(duì)象
private RestHighLevelClient client;
// 需要從數(shù)據(jù)庫(kù)中查數(shù)據(jù)存入es,裝配業(yè)務(wù)
@Autowired(required = false)
private IHotelService service;
@BeforeEach
void setUp(){
this.client = new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://localhost:9200")
));
}
@AfterEach
void tearDown() throws Exception{
this.client.close();
}
// 從數(shù)據(jù)庫(kù)新增一條數(shù)據(jù)到es
@Test
void addDocument() throws Exception{
// 從數(shù)據(jù)庫(kù)查詢(xún)一條數(shù)據(jù)
Hotel hotel = service.getById(395434);
System.out.println(hotel);
// 轉(zhuǎn)換為文檔類(lèi)型
HotelDoc hotelDoc = new HotelDoc(hotel);
// 將文檔類(lèi)型轉(zhuǎn)為JSON格式
String json = JSON.toJSONString(hotelDoc);
// 準(zhǔn)備request請(qǐng)求對(duì)象
IndexRequest request = new IndexRequest("hotels").id(hotelDoc.getId().toString());
// 準(zhǔn)備JSON文檔
request.source(json, XContentType.JSON);
// 發(fā)送請(qǐng)求
client.index(request, RequestOptions.DEFAULT);
}
// 從es中刪除一條數(shù)據(jù)
@Test
void deleteDocument() throws Exception{
// 準(zhǔn)備刪除請(qǐng)求Request
DeleteRequest request = new DeleteRequest("hotels", "395434");
// 發(fā)送請(qǐng)求
client.delete(request,RequestOptions.DEFAULT);
}
// 修改es中的數(shù)據(jù)
@Test
void updateDocument() throws Exception{
// 準(zhǔn)備修改請(qǐng)求UpdateRequest
UpdateRequest request = new UpdateRequest("hotels", "395434");
// 準(zhǔn)備請(qǐng)求參數(shù)(要修改的數(shù)據(jù)內(nèi)容)
request.doc(
"name","W酒店",
"city","西安",
"price","2000",
"starName","五星級(jí)"
);
// 發(fā)送請(qǐng)求
client.update(request, RequestOptions.DEFAULT);
}
// 從es中查詢(xún)一條數(shù)據(jù)
@Test
void getDocumentById() throws Exception{
// 準(zhǔn)備查詢(xún)請(qǐng)求GetRequest
GetRequest getRequest = new GetRequest("hotels", "395434");
// 發(fā)送請(qǐng)求,得到響應(yīng)
GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);
// 解析響應(yīng)結(jié)果
String json = response.getSourceAsString();
HotelDoc hotelDoc = JSON.parseObject(json,HotelDoc.class);
System.out.println(hotelDoc);
}
// 批量新增數(shù)據(jù)到es
@Test
void addAllDocument() throws Exception{
// 數(shù)據(jù)庫(kù)全查
List<Hotel> hotels = service.list();
// 準(zhǔn)備請(qǐng)求
BulkRequest bulkRequest = new BulkRequest();
// 準(zhǔn)備參數(shù)
for(Hotel hotel : hotels){
// 類(lèi)型轉(zhuǎn)化
HotelDoc hotelDoc = new HotelDoc(hotel);
// 請(qǐng)求添加數(shù)據(jù)
bulkRequest.add(new IndexRequest("hotels").id(hotelDoc.getId().toString()).source(JSON.toJSONString(hotelDoc),XContentType.JSON));
}
// 發(fā)送請(qǐng)求
client.bulk(bulkRequest,RequestOptions.DEFAULT);
}
// 解析對(duì)象方法
public void show(SearchResponse response){
// 解析響應(yīng)
SearchHits searchHits = response.getHits();
long total = searchHits.getTotalHits().value;
System.out.println("總計(jì)查詢(xún)數(shù)據(jù):"+total+"條");
SearchHit[] hits = searchHits.getHits();
for(SearchHit hit :hits){
/// 獲取文檔source
String json = hit.getSourceAsString();
// 反序列化
HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
System.out.println("hotelDoc="+hotelDoc);
}
}
/*---------- 全查 ------------*/
// 全查
@Test
void findAllDocument() throws IOException{
// 準(zhǔn)備request
SearchRequest request = new SearchRequest("hotels");
// 2.準(zhǔn)備DSL,QueryBuilders構(gòu)造查詢(xún)條件
request.source().query(QueryBuilders.matchAllQuery());
// 3.發(fā)送請(qǐng)求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
show(response);
}
/*-------------- 全文檢索 ---------------*/
// 查詢(xún)all字段內(nèi)容中含有如家的
@Test
void testMacth() throws IOException{
// 準(zhǔn)備請(qǐng)求
SearchRequest request = new SearchRequest("hotels");
// 準(zhǔn)備DSL
request.source().
query(QueryBuilders.matchQuery("all","如家"));
// 發(fā)送請(qǐng)求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
show(response);
}
// 查詢(xún)字段name、city中有上海的
@Test
void testMultiMatchQuery()throws IOException {
// 準(zhǔn)備請(qǐng)求
SearchRequest request = new SearchRequest("hotels");
// 準(zhǔn)備DSL
request.source()
.query(QueryBuilders.multiMatchQuery("上海","name","city"));
// 發(fā)送請(qǐng)求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
show(response);
}
/*------------ 精確查詢(xún) ------------------*/
// term:根據(jù)詞條精準(zhǔn)查詢(xún)(字段等值查詢(xún))
@Test
void testTerm() throws IOException{
// 準(zhǔn)備請(qǐng)求
SearchRequest request = new SearchRequest("hotels");
// 準(zhǔn)備DSL
request.source()
.query(QueryBuilders.termQuery("brand","希爾頓"));
// 發(fā)送請(qǐng)求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
show(response);
}
// range范圍查詢(xún)
@Test
void testRange() throws IOException {
// 準(zhǔn)備請(qǐng)求
SearchRequest request = new SearchRequest("hotels");
// 準(zhǔn)備DSL
request.source()
.query(QueryBuilders.rangeQuery("price").gte(200).lte(300));
// 發(fā)送請(qǐng)求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
show(response);
}
// ids查詢(xún)
@Test
void testIds() throws IOException {
// 準(zhǔn)備請(qǐng)求
SearchRequest request = new SearchRequest("hotels");
// 準(zhǔn)備DSL
request.source()
.query(QueryBuilders.idsQuery().addIds("395434","3532"));
// 發(fā)送請(qǐng)求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
show(response);
}
/*------------- 復(fù)合查詢(xún) --------------------*/
// bool復(fù)合查詢(xún)
@Test
void testBool() throws IOException{
// 準(zhǔn)備請(qǐng)求
SearchRequest request = new SearchRequest("hotels");
// 準(zhǔn)備條件
/*-- 方式1 ----*/
// BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
// boolQueryBuilder.must(QueryBuilders.termQuery("city","北京"));
// boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(500));
// // 準(zhǔn)備DSL
// request.source().query(boolQueryBuilder);
/*---- 方式2 ----*/
request.source()
.query(QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery("city","北京"))
.filter(QueryBuilders.rangeQuery("price").lte(500)));
// 發(fā)送請(qǐng)求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
show(response);
}
// 自定義分頁(yè)方式
@Test
void testPageAndSort() throws IOException{
int page = 1; //頁(yè)碼
int size = 5; //步長(zhǎng)
String searchName="希爾頓"; // 查詢(xún)條件
// 準(zhǔn)備請(qǐng)求
SearchRequest request = new SearchRequest("hotels");
if (searchName == null){
request.source().query(QueryBuilders.matchAllQuery());
}else {
request.source().query(QueryBuilders.matchQuery("brand",searchName));
}
// 自定義分頁(yè)
request.source().from((page-1)*size).size(size);
// 自定義排序
request.source().sort("price", SortOrder.DESC);
// 發(fā)送請(qǐng)求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 解析結(jié)果
show(response);
}
}
小結(jié):文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-760041.html
文檔的查詢(xún)操作實(shí)現(xiàn)步驟大致都相同:文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-760041.html
- 準(zhǔn)備請(qǐng)求
- 準(zhǔn)備DSL
- 發(fā)送請(qǐng)求
到了這里,關(guān)于SpringBoot--中間件技術(shù)-3:整合mongodb,整合ElasticSearch,附案例含代碼(簡(jiǎn)單易懂)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!