Spring Boot 全文搜索与 MySQL 数据库教程

Spring Boot 全文搜索与 MySQL 数据库教程,第1张

通过这篇 Spring Boot 教程,我想和大家分享一下如何在一个基于 Spring 框架的 Java Web 应用程序中,使用 MySQL 数据库实现全文搜索功能。详细地,您将了解到:

  • 为什么使用全文搜索,它与完全匹配搜索有何不同?
  • 在 MySQL 数据库中创建全文索引
  • 使用 Spring Data JPA 编写全文搜索查询
  • 在应用程序的服务层、控制器层和视图层实现搜索功能

我想您正在开发一个包含产品列表功能的 Spring Boot 项目。现在你想用全文搜索来实现产品搜索功能。

技术:Spring 框架、Spring Boot、Spring MVC、Spring Data JPA、Hibernate、Thymleaf、Bootstrap。

软件程序:Java Development Kit (JDK)、Java IDE(Eclipse、Spring Tool Suite、IntelliJ…)、MySQL 数据库服务器和 MySQL Workbench。

1. 为什么要全文搜索?

简而言之,全文搜索比精确匹配搜索提供更相关、更自然的结果。以下屏幕截图显示了关键字“iphone 7”的精确匹配搜索结果:

 使用完全匹配搜索,结果仅显示名称或描述中包含“iphone 7”一词的产品。但是对于全文搜索,结果将如下所示(对于相同的关键字):

 你看,除了iPhone 7,它还返回了iPhone XS、iPhone X、iPhone 6S……这对最终用户更有帮助,对吧?

此外,全文搜索提供高级搜索选项,如自然语言查询和特殊搜索运算符,具体取决于数据库引擎。


2.在MySQL数据库中创建全文索引

MySQL 使在表上启用全文搜索变得简单易行。假设我们有包含以下列的表product :

CREATE TABLE `product` (
	`id` INT(10) NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(256) NOT NULL COLLATE 'utf8mb4_unicode_ci',
	`alias` VARCHAR(256) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
	`brief` VARCHAR(1024) NOT NULL COLLATE 'utf8mb4_unicode_ci',
	`detail` LONGTEXT NOT NULL COLLATE 'utf8mb4_unicode_ci',
	PRIMARY KEY (`id`) USING BTREE
)
COLLATE='utf8mb4_unicode_ci'
ENGINE=InnoDB
;

并且我们需要实现产品搜索功能,允许用户输入关键字,它将搜索 3 列中的信息:namebriefdetail

然后我们需要为这个表中的这些列创建一个 FULLTEXT 索引。在 MySQL Workbench 中更改表,单击 Indexes 选项卡。输入类型为FULLTEXT的新索引名称full_text_index(或任何唯一名称),

然后在索引列中,检查 3 列namebriefdetai。然后单击应用按钮以保存更改。

或者,您可以执行以下 SQL 语句来创建索引:

ALTER TABLE `dbname`.`product`
ADD FULLTEXT INDEX `full_text_index` (`name`, `brief`, `detail`) VISIBLE;

一旦创建全文索引,MySQL 将立即自动启动索引进程。并且默认搜索模式是自然语言。

现在,您可以尝试执行以下 SQL Select 查询来测试全文索引:

SELECT id, name FROM fulltextdb.product
WHERE MATCH (name, brief, detail) AGAINST ('apple 7');

结果将是这样的:

默认情况下,结果按与给定关键字匹配的行的相关性排序。如果您想将相关性视为分数数字,请执行此查询:

SELECT id, name, MATCH (name, brief, detail) AGAINST ('apple 7') as score
FROM product WHERE MATCH (name, brief, detail) AGAINST ('apple 7');

结果将是这样的:

 您还可以在使用 SQL 脚本创建新表时指定 FULLTEXT 索引。例如:

CREATE TABLE `product` (
	`id` INT(10) NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(256) NOT NULL COLLATE 'utf8mb4_unicode_ci',
	`alias` VARCHAR(256) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
	`brief` VARCHAR(1024) NOT NULL COLLATE 'utf8mb4_unicode_ci',
	`detail` LONGTEXT NOT NULL COLLATE 'utf8mb4_unicode_ci',
	PRIMARY KEY (`id`) USING BTREE,
	FULLTEXT INDEX `full_text_index` (`name`, `brief`, `detail`)
)
COLLATE='utf8mb4_unicode_ci'
ENGINE=InnoDB
;

阅读此MySQL 文档以了解有关 MySQL 中的全文搜索功能的更多信息。


3. 使用 Spring Data JPA 编写全文搜索查询

接下来,让我们在我们的 Spring Boot 项目中更新存储库层,用于声明全文搜索方法,如下所示:

package net.codejava;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
// import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.PagingAndSortingRepository;

// public interface ProductRepository extends JpaRepository {
public interface ProductRepository extends PagingAndSortingRepository {

    @Query("SELECT p FROM Product p WHERE " + "CONCAT(p.id, ' ', p.name, ' ' , p.alias, ' ' , p.brief, ' ' , p.detail)"
            + "LIKE %?1%")
    public Page findAll(String keyword, Pageable pageable);

    @Query(value = "SELECT * FROM product WHERE MATCH(name, brief, detail) "
            + "AGAINST (?1)", nativeQuery = true
    )
    public Page search(String keyword, Pageable pageable);

}

你看,因为全文搜索是依赖于数据库的,所以我们需要声明一个原生查询,在这个例子中就是 MySQL 查询。请注意,search()方法需要Pageable类型的第二个参数,这意味着搜索结果可以分页。

实体类

package net.codejava;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Product {

    private Long id;
    private String name;
    private String alias;
    private String brief;
    private String detail;

    public Product() {
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAlias() {
        return alias;
    }

    public void setAlias(String alias) {
        this.alias = alias;
    }

    public String getBrief() {
        return brief;
    }

    public void setBrief(String brief) {
        this.brief = brief;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail;
    }

}

4.在服务层实现搜索功能

接下来,我们需要更新服务层,以实现搜索功能。像这样更新ProductService类:

package net.codejava;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

@Service
public class ProductService {

    @Autowired
    private ProductRepository repo;

    public Page listAll(int pageNumber, String sortField, String sortDir, String keyword) {

        Sort sort = Sort.by(sortField);
        sort = sortDir.equals("asc") ? sort.ascending() : sort.descending();

        Pageable pageable = PageRequest.of(pageNumber - 1, 7, sort); // 7 rows per page

        if (keyword != null) {
            return repo.findAll(keyword, pageable);
        }
        return repo.findAll(pageable);
    }

    public void save(Product product) {
        repo.save(product);
    }

    public Product get(Long id) {
        return repo.findById(id).get();
    }

    public void delete(Long id) {
        repo.deleteById(id);
    }

    public static final int SEARCH_RESULT_PER_PAGE = 10;

    public Page search(String keyword, int pageNum) {
        Pageable pageable = PageRequest.of(pageNum - 1, SEARCH_RESULT_PER_PAGE);
        return repo.search(keyword, pageable);
    }
}

5.在控制器层实现搜索功能

接下来,我们需要更新控制器层,用于处理搜索请求并返回搜索结果。下面是一个示例,展示了如何在控制器层中实现搜索功能:

package net.codejava;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class AppController {

    @Autowired
    private ProductService service;

    @RequestMapping("/")
    public String viewHomePage(Model model) {
        // String keyword = "reebok";
        String keyword = null;

        /*
		 * if (keyword != null) { return listByPage(model, 1, "name", "asc", keyword); }
         */
        return listByPage(model, 1, "name", "asc", keyword);

    }

    @GetMapping("/page/{pageNumber}")
    public String listByPage(Model model, @PathVariable("pageNumber") int currentPage,
            @Param("sortField") String sortField, @Param("sortDir") String sortDir, @Param("keyword") String keyword) {

        Page page = service.listAll(currentPage, sortField, sortDir, keyword);

        long totalItems = page.getTotalElements();
        int totalPages = page.getTotalPages();
        // int currentPage = page.previousPageable().getPageNumber();

        List listProducts = page.getContent();

        model.addAttribute("totalItems", totalItems);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("currentPage", currentPage);
        model.addAttribute("listProducts", listProducts); // next bc of thymeleaf we make the index.html

        model.addAttribute("sortField", sortField);
        model.addAttribute("sortDir", sortDir);
        model.addAttribute("keyword", keyword);

        String reverseSortDir = sortDir.equals("asc") ? "desc" : "asc";
        model.addAttribute("reverseSortDir", reverseSortDir);

        return "index";
    }

    @RequestMapping("/new")
    public String showNewProductForm(Model model) {
        Product product = new Product();
        model.addAttribute("product", product);

        return "new_product";
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String saveProduct(@ModelAttribute("product") Product product) {
        service.save(product);

        return "redirect:/";
    }

    @RequestMapping("/edit/{id}")
    public ModelAndView showEditProductForm(@PathVariable(name = "id") Long id) {
        ModelAndView modelAndView = new ModelAndView("edit_product");
        Product product = service.get(id);
        modelAndView.addObject("product", product);

        return modelAndView;
    }

    @RequestMapping("/delete/{id}")
    public String deleteProduct(@PathVariable(name = "id") Long id) {
        service.delete(id);

        return "redirect:/";
    }

    @GetMapping("/search")
    public String search(String keyword, Model model) {
        return searchByPage(keyword, model, 1);
    }

    @GetMapping("/search/page/{pageNum}")
    public String searchByPage(String keyword, Model model,
            @PathVariable(name = "pageNum") int pageNum) {

        Page result = service.search(keyword, pageNum);

        List listResult = result.getContent();

        model.addAttribute("totalPages", result.getTotalPages());
        model.addAttribute("totalItems", result.getTotalElements());
        model.addAttribute("currentPage", pageNum);

        long startCount = (pageNum - 1) * ProductService.SEARCH_RESULT_PER_PAGE + 1;
        model.addAttribute("startCount", startCount);

        long endCount = startCount + ProductService.SEARCH_RESULT_PER_PAGE - 1;
        if (endCount > result.getTotalElements()) {
            endCount = result.getTotalElements();
        }

        model.addAttribute("endCount", endCount);
        model.addAttribute("listResult", listResult);
        model.addAttribute("keyword", keyword);

        return "search_result";
    }

}

启动类

package net.codejava;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ProductManagerApplication {

	public static void main(String[] args) {
		SpringApplication.run(ProductManagerApplication.class, args);
	}

}
6. 为搜索功能更新视图层

最后,我们需要使用 HTML、Thymeleaf 和 Bootstrap 代码更新视图层。使用以下代码将搜索表单放入每个页面的标题中:

index.html





    
        
        Product Manager
    

    
        
            
                Product Manager
                Create New Product 

 
Filter:    
 
Product ID Name Alias Brief Detail Actions
Product ID Name Alias Brief Detail Edit     Delete
    Total items: [[${totalItems}]] - Page [[${currentPage}]] of [[${totalPages}]]     1}" th:href="@{'/page/1?sortField=' + ${sortField} + '&sortDir=' + ${sortDir} + ${keyword != null ? '&keyword=' + keyword : ''}}">First First    1}" th:href="@{'/page/' + ${currentPage - 1} + '?sortField=' + ${sortField} + '&sortDir=' + ${sortDir} + ${keyword != null ? '&keyword=' + keyword : ''}}">Previous Previous    [[${i}]]     [[${i}]]     Next Next    Last Last   

这是搜索结果页面的示例:

search_result.html



    
        
        
        Search Result
    
    
        

            
                Search Results for '[[${keyword}]]'
                
[[${product.name}]]
[[${product.brief}]]
[[${product.detail}]]
0}"> Showing results # [[${startCount}]] to [[${endCount}]] of [[${totalItems}]] 0}"> No match found for keyword '[[${keyword}]]'.
edit_product.html


    
        
            Edit product
    
    
        
            Edit product
            
Product ID:
Product Name:
Alias
Brief:
Detail:

new_product.html



    
        
            Create new product
    
    
        
            Create new product
            
Product Name:
Alias:
Brief:
Detail:

要显示分页按钮,请参阅这篇文章:Spring Data JPA 分页和排序示例

运行输出

 

 


7. MySQL全文搜索的优缺点

MySQL 提供了内置的全文搜索功能,这使得将全文搜索功能集成到您的应用程序中变得简单易行。全文搜索适用于单个表格。但是,如果查询涉及到多个表,这将是困难和复杂的。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/916509.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存