Solr查询实际应用

Solr查询实际应用

核心代码为第五步, 实现类

1. 导入依赖

<!-- 主要依赖 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-solr</artifactId>
</dependency>
<!-- lombok -->
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
</dependency>

2. application.yml配置文件

配置solr服务器

spring:
  data:
    solr:   #注意修改ip地址
      host: http://192.168.64.170:8983/solr/pd

3. Item 实体类

对应数据库中的item表

package com.pd.pojo;

import java.io.Serializable;

import org.apache.solr.client.solrj.beans.Field;

import lombok.Data;

@Data
public class Item implements Serializable {
		private static final long serialVersionUID = 1L;
		
		@Field("id") // 此注解用于建立映射关系, 方便把json转对item对象
		private String id;
		@Field("title")
		private String title;
		@Field("sellPoint")
		private String sellPoint;
		@Field("price")
		private Long price;
		@Field("image")
		private String image;

}

4. SearchService 接口

package com.pd.service;

import java.util.List;

import com.pd.pojo.Item;

public interface SearchService {
	List<Item> findItemByKey(String key) throws Exception;
}

5. SearchServiceImpl 实现类

package com.pd.service.impl;

import java.util.List;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import com.pd.pojo.Item;
import com.pd.service.SearchService;

@Service
public class SearchServiceImpl implements SearchService {
	
	/*
	 * SolrClient实例是在 SolrAutoConfiguration 类中创建的
	 * 
	 * SolrAutoConfiguration添加了@Configuration注解,
	 * 是spring boot自动配置类,其中的solrClient()方法中创建了SolrClient实例
	 */
	@Autowired
	private SolrClient solrClient;

	@Override
	public List<Item> findItemByKey(String key) throws Exception {
		//封装查询的关键词
		//也可以封装其他的查询参数,比如指定字段,facet设置等
		SolrQuery query = new SolrQuery(key);
		//查询前多少条数据
		query.setStart(0);
		query.setRows(20);
		
		//执行查询并得到查询结果
		QueryResponse qr = solrClient.query(query);
		//把查询结果转成一组商品实例
		List<Item> beans = qr.getBeans(Item.class);
		return beans;
	}

}

6. SearchController 控制器

主要用户向前端发送数据, 前端页面略

package com.pd.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import com.pd.pojo.Item;
import com.pd.service.SearchService;

@Controller
public class SearchController {
	@Autowired
	private SearchService searchService;
	
	@GetMapping("/search/toSearch.html")
	public String search(String key, Model model) throws Exception {
		List<Item> itemList = searchService.findItemByKey(key);
		model.addAttribute("list", itemList);
		return "/search.jsp";
	}
}
posted @ 2020-09-10 16:20  zpk-aaron  阅读(214)  评论(0编辑  收藏  举报