Skip to content

Commit

Permalink
add: elasticsearch
Browse files Browse the repository at this point in the history
  • Loading branch information
hoangtien2k3 committed Jun 20, 2024
1 parent fd0cfc0 commit 155b87a
Show file tree
Hide file tree
Showing 17 changed files with 134 additions and 24 deletions.
4 changes: 4 additions & 0 deletions .env
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ REDIS_TAG=7.2.3
REDIS_PORT=6379
REDIS_HOST=redis-container

# elasticsearch
ELASTICSEARCH_TAG=7.17.22
ELASTICSEARCH_PORT=9200

# neo4j
NEO4J_TAG=4.4.34
NEO4J_HTTP_PORT=7474
Expand Down
14 changes: 14 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,18 @@ services:
networks:
- shopapp-network

# elastic search
elasticsearch-container:
container_name: elasticsearch-container
image: elasticsearch:${ELASTICSEARCH_TAG}
ports:
- "${ELASTICSEARCH_PORT}:9200"
environment:
- "discovery.type=single-node"
- "xpack.security.enabled=false"
networks:
- shopapp-network

# neo4j
neo4j-container:
container_name: neo4j-container
Expand Down Expand Up @@ -171,3 +183,5 @@ networks:
# docker-compose up -d zookeeper-03
# docker-compose up -d kafka-broker-01
# docker-compose up -d shopapp-spring-container


4 changes: 4 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,10 @@
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-data-elasticsearch</artifactId>-->
<!-- </dependency>-->
</dependencies>

<build>
Expand Down
Binary file modified redis-data/dump.rdb
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
//@EnableJpaRepositories(basePackages = "com.hoangtien2k3.shopappbackend.repositories.ProductRepository", enableDefaultTransactions = false)
//@EnableElasticsearchRepositories(basePackages = "com.hoangtien2k3.shopappbackend.repositories.ProductSearchRepository", considerNestedRepositories = true, enableDefaultTransactions = false)
public class ShopappBackendApplication {

public static void main(String[] args) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
Expand Down Expand Up @@ -300,6 +301,17 @@ public ResponseEntity<?> deleteProductById(@PathVariable("id") Long id) {
}
}

// Endpoint to search products by keyword
// @GetMapping("/search")
// public Page<ProductResponse> searchProducts(
// @RequestParam String keyword,
// @RequestParam(defaultValue = "0") int page,
// @RequestParam(defaultValue = "10") int size
// ) {
// PageRequest pageRequest = PageRequest.of(page, size, Sort.by(Sort.Direction.ASC, "name"));
// return productService.searchProducts(keyword, pageRequest);
// }

// fack dữ liệu
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/generate-faceker-products")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@
@NoArgsConstructor
@Getter
@Setter
/**
* @MappedSuperclass
* Chia sẻ thuộc tính: kế thừa các thuộc tính, phương thức, và ánh xạ từ lớp siêu lớp mà không cần định nghĩa lại.
* Không tạo bảng riêng: Lớp được chú thích với @MappedSuperclass sẽ không tạo ra một bảng trong cơ sở dữ liệu.
* Thay vào đó, các thuộc tính của nó sẽ được ánh xạ vào các bảng của các lớp con.
* */
@MappedSuperclass
public class BaseEntity {
@JsonProperty("created_at")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*;
import lombok.*;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import java.util.ArrayList;
import java.util.List;
Expand All @@ -14,6 +13,7 @@
@Setter
@Builder
@Entity
//@Document(indexName = "products")
@Table(name = "products")
@EntityListeners(ProductListener.class) // Envent-driven approach SPRING DATA JPA
public class Product extends BaseEntity {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.hoangtien2k3.shopappbackend.repositories;

import com.hoangtien2k3.shopappbackend.models.Order;
import com.hoangtien2k3.shopappbackend.utils.ConfixSql;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
Expand All @@ -13,9 +14,6 @@ public interface OrderRepository extends JpaRepository<Order, Long> {
List<Order> findByUserId(Long userId);

// lẩy ra tất cả các order
@Query("SELECT o FROM Order o WHERE " +
"(:keyword IS NULL OR :keyword = '' OR o.fullName LIKE %:keyword% OR o.address LIKE %:keyword% " +
"OR o.note LIKE %:keyword%)"
)
@Query(ConfixSql.Order.GET_ALL_ORDER)
Page<Order> findByKeyword(String keyword, Pageable pageable);
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.hoangtien2k3.shopappbackend.repositories;

import com.hoangtien2k3.shopappbackend.models.Product;
import com.hoangtien2k3.shopappbackend.utils.ConfixSql;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
Expand All @@ -14,18 +15,15 @@ public interface ProductRepository extends JpaRepository<Product, Long> {

Page<Product> findAll(Pageable pageable);

@Query("SELECT p FROM Product p WHERE " +
"(:categoryId IS NULL OR :categoryId = 0 OR p.category.id = :categoryId) " +
"AND (:keyword IS NULL OR :keyword = '' OR LOWER(p.name) LIKE LOWER(CONCAT('%', :keyword, '%')) " +
"OR LOWER(p.description) LIKE LOWER(CONCAT('%', :keyword, '%')))")
@Query(ConfixSql.Product.SEARCH_PRODUCT_BY_KEYWORD)
Page<Product> searchProducts(@Param("keyword") String keyword,
@Param("categoryId") Long categoryId,
Pageable pageable);

@Query("SELECT p FROM Product p LEFT JOIN FETCH p.productImages where p.id = :productId")
@Query(ConfixSql.Product.GET_DETAIL_PRODUCT)
Optional<Product> getDetailProducts(@Param("productId") Long productId);

@Query("SELECT p FROM Product p where p.id IN :productIds")
@Query(ConfixSql.Product.FIND_PRODUCT_BY_IDS)
List<Product> findProductByIds(@Param("productIds") List<Long> productIds);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
//package com.hoangtien2k3.shopappbackend.repositories;
//
//import com.hoangtien2k3.shopappbackend.models.Product;
//import org.springframework.context.annotation.Primary;
//import org.springframework.data.domain.Page;
//import org.springframework.data.domain.Pageable;
//import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
//
//public interface ProductSearchRepository extends ElasticsearchRepository<Product, Long> {
// Page<Product> findByNameContainingOrDescriptionContaining(String name, String description, Pageable pageable);
//}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.hoangtien2k3.shopappbackend.repositories;

import com.hoangtien2k3.shopappbackend.models.User;
import com.hoangtien2k3.shopappbackend.utils.ConfixSql;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
Expand All @@ -15,10 +16,6 @@ public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByPhoneNumber(String phoneNumber);

// lấy ra tất cả user (ngoại trừ admin) với truyền admin
@Query("SELECT o FROM User o WHERE o.active = true AND (:keyword IS NULL OR :keyword = '' " +
"OR o.fullName LIKE %:keyword% " +
"OR o.address LIKE %:keyword% " +
"OR o.phoneNumber LIKE %:keyword%) " +
"AND LOWER(o.role.name) = 'user'")
@Query(ConfixSql.User.GET_ALL_USER)
Page<User> fillAll(@Param("keyword") String keyword, Pageable pageable);
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,12 @@ List<ProductResponse> getAllProducts(String keyword,
Long categoryId,
PageRequest pageRequest,
String sortField,
String sortDirection
) throws JsonProcessingException;
String sortDirection) throws JsonProcessingException;

void saveAllProducts(List<ProductResponse> productResponses,
String keyword,
Long categoryId,
PageRequest pageRequest,
String sortField,
String sortDirection
) throws JsonProcessingException;
String sortDirection) throws JsonProcessingException;
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,7 @@ ProductImage createProductImage(Long productId,
Product getDetailProducts(long productId) throws Exception;

List<Product> findProductsByIds(List<Long> productIds);

// Elasticsearch
// Page<ProductResponse> searchProducts(String keyword, PageRequest pageRequest);
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@
import com.hoangtien2k3.shopappbackend.repositories.CategoryRepository;
import com.hoangtien2k3.shopappbackend.repositories.ProductImageRepository;
import com.hoangtien2k3.shopappbackend.repositories.ProductRepository;
//import com.hoangtien2k3.shopappbackend.repositories.ProductSearchRepository;
import com.hoangtien2k3.shopappbackend.responses.product.ProductResponse;
import com.hoangtien2k3.shopappbackend.services.ProductService;
import com.hoangtien2k3.shopappbackend.utils.LocalizationUtils;
import com.hoangtien2k3.shopappbackend.utils.MessageKeys;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
Expand All @@ -29,13 +29,13 @@

@Service
@RequiredArgsConstructor
public class ProductServiceImpl extends TranslateMessages
implements ProductService {
public class ProductServiceImpl extends TranslateMessages implements ProductService {

private final ProductRepository productRepository;
private final CategoryRepository categoryRepository;
private final ProductImageRepository productImageRepository;
private final ProductMapper productMapper;
// private final ProductSearchRepository productSearchRepository;

@Override
@Transactional
Expand Down Expand Up @@ -151,4 +151,15 @@ public List<Product> findProductsByIds(List<Long> productIds) {
return productRepository.findProductByIds(productIds);
}

// @Override
// public Page<ProductResponse> searchProducts(String keyword, PageRequest pageRequest) {
// Pageable pageable = PageRequest.of(
// pageRequest.getPageNumber(),
// pageRequest.getPageSize(),
// Sort.by(Sort.Direction.ASC, "name")
// );
// Page<Product> productPage = productSearchRepository.findByNameContainingOrDescriptionContaining(keyword, keyword, pageable);
// return productPage.map(ProductResponse::fromProduct);
// }

}
43 changes: 43 additions & 0 deletions src/main/java/com/hoangtien2k3/shopappbackend/utils/ConfixSql.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.hoangtien2k3.shopappbackend.utils;

public class ConfixSql {

public interface Product {
// Tìm kiếm sản phẩm theo từ khóa và id danh mục
String SEARCH_PRODUCT_BY_KEYWORD = "SELECT p FROM Product p WHERE " +
"(:categoryId IS NULL OR :categoryId = 0 OR p.category.id = :categoryId) " +
"AND (:keyword IS NULL OR :keyword = '' OR LOWER(p.name) LIKE LOWER(CONCAT('%', :keyword, '%')) " +
"OR LOWER(p.description) LIKE LOWER(CONCAT('%', :keyword, '%')))";

// lấy ra chi tiết sản phẩm theo id
String GET_DETAIL_PRODUCT = "SELECT p FROM Product p LEFT JOIN FETCH p.productImages where p.id = :productId";

// tìm kiếm sản phẩm theo danh sách id
String FIND_PRODUCT_BY_IDS = "SELECT p FROM Product p where p.id IN :productIds";
}

public interface Category {
// lấy ra tất cả danh mục sản phẩm
String GET_ALL_CATEGORY = "SELECT c FROM Category c WHERE c.active = true";

// lấy ra danh mục sản phẩm theo id
String GET_CATEGORY_BY_ID = "SELECT c FROM Category c WHERE c.id = :categoryId";
}

public interface User {
// lấy ra tất cả user (ngoại trừ admin) với truyền admin
String GET_ALL_USER = "SELECT o FROM User o WHERE o.active = true AND (:keyword IS NULL OR :keyword = '' " +
"OR o.fullName LIKE %:keyword% " +
"OR o.address LIKE %:keyword% " +
"OR o.phoneNumber LIKE %:keyword%) " +
"AND LOWER(o.role.name) = 'user'";
}

public interface Order {
// lẩy ra tất cả các order
String GET_ALL_ORDER = "SELECT o FROM Order o WHERE " +
"(:keyword IS NULL OR :keyword = '' OR o.fullName LIKE %:keyword% OR o.address LIKE %:keyword% " +
"OR o.note LIKE %:keyword%)";
}

}
10 changes: 9 additions & 1 deletion src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,20 @@ spring:
baseline-on-migrate: true # phiên bản baseline = 1, không thực hiện bất kỳ thay đổi nào trong DB
baseline-version: 0 # nó sẽ chạy V1__alter_some_tables.sql -> nghĩa là nó sẽ chạy cái version lớn hơn cái version hiện tại của chúng ta

#redis memory

data:
#redis memory
redis:
host: ${REDIS_HOST:localhost}
port: ${REDIS_PORT:6379}

# elastic search
# elasticsearch:
# rest:
# uris: http://localhost:9200
# repositories:
# enabled: true

# kafka
kafka:
bootstrap-servers: localhost:9092
Expand Down

0 comments on commit 155b87a

Please sign in to comment.