Later additions:
Why use solr service, why use luncence?
The question is: When we visit a shopping website, we can enter keywords based on the content we want to query the relevant content. How can we do this? These random data cannot be queried based on the database fields. How are they queried? Why can all kinds of strange keywords be queried?
The answer is the implementation of the full-text search tool, and luncence uses word-element matching and word segmentation. For example: Beijing Tiananmen Square------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- So we can search it when we search.
There is a word segmenter that is the IKAnalyzer Chinese word segmenter, which has fine-grained slicing and intelligent slicing, that is, according to a certain intelligent algorithm.
This is the biggest benefit of using solr: the implementation of the search function.
Steps for use;
(1) Solr server is built, because Solr is developed using Java5, so jdk and tomcat are needed. Build and deploy
(2) After the construction is completed, we need to introduce the fields to be displayed into the solr library. Configure spring and solr to start solr when the project starts
(3) Import the query content in the database into the solr index library, which is implemented by the solrj client. For specific use, please refer to the api
(4) Establish a search service for client calls. Call solr to query the content, there is an implementation of the paging function. Implementation of solr highlighting.
(5) The client receives the request parameters of the page, calls the search service, and conducts search.
Business field judgment criteria:
1. Whether searching on this field is required. For example: product name, product selling point, product description
(These are equivalent to giving the label to solr. After importing the product data, solr divides the specific content of the corresponding products in these fields, and then we can search for relevant content)
2. Whether this field is required for subsequent business. For example: product id.
Required fields:
1. Product ID
2. Product title
3. Selling points
4. Price
5. Product pictures
6. Product category name
7. Product Description
Business fields in Solr:
1. id--》Product id
Other corresponding fields create the fields of solr.
<field name="item_title" type="text_ik" indexed="true" stored="true"/><field name="item_sell_point" type="text_ik" indexed="true" stored="true"/><field name="item_price" type="long" indexed="true" stored="true" stored="true"/><field name="item_image" type="string" indexed="false" stored="true" /><field name="item_category_name" type="string" indexed="true" stored="true" /><field name="item_desc" type="text_ik" indexed="true" stored="false" /> <field name="item_keywords" type="text_ik" indexed="true" stored="false" multiValued="true"/><copyField source="item_title" dest="item_keywords"/><copyField source="item_sell_point" dest="item_keywords"/><copyField source="item_category_name" dest="item_keywords"/><copyField source="item_desc" dest="item_keywords"/><copyField source="item_desc" dest="item_keywords"/><copyField source="item_desc" dest="item_keywords"/>
Restart tomcat
Solr is a top open source project under Apache, developed in Java, and is a full-text search server based on Lucene. Solr provides a richer query language than Lucene, and at the same time it is configurable and extensible, and optimizes index and search performance.
Solr is a full-text search server, and can realize full-text search service only by configuring it. Effectively reduce the pressure on the database due to frequent access to the database.
Step 1: Deploy solr on the Linux system.
Step 2: solrJ is solr's client, and using it requires relying on solrJ's jar package.
Step 3: Add the content of the database to the solr's index library, so that the query will be queryed in the index library, not the database.
Controller layer:
@Controller@RequestMapping("/manager")public class ItemController { @Autowired private ItemService itemService; @RequestMapping("/importall") @ResponseBody public TaotaoResult importAllItem(){ TaotaoResult result= itemService.importAllItem(); return result; }}<br>service layer writing: <br>Multi-table query product, logic writing displayed on the page: <br>mapper.java package com.taotao.search.mapper; import java.util.List; import com.taotao.search.pojo.Item; public interface ItemMapper { List<Item> getItemList(); }mappper.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapper namespace="com.taotao.search.mapper.ItemMapper"><select id="getItemList" resultType="com.taotao.search.pojo.Item"> SELECT a.id, a.title, a.sell_point, a.price, a.image, b. NAME category_name FROM tb_item a LEFT JOIN tb_item_cat b ON a.cid = b.id</select></mapper>
Step 4: Write the logic of query from the index library:
//Get product information from the index library. Now this dao layer is to obtain information from the index library, because the previous writing logic was to import the data in the db into the index library. The subsequent queries are all conducted from the index library, not from the database @Repositorypublic class SearchDaoImpl implements SearchDao { @Autowired private SolrServer solrServer; @Override public SearchResult search(SolrQuery query) throws Exception { //This is to directly execute the query from the index library QueryResponse response = solrServer.query(query); //Get the result of the query SolrDocumentList documentList= response.getResults(); SearchResult result=new SearchResult(); //This is to get the total number of records result.setRecordCount(documentList.getNumFound()); List<Item> itemList=new ArrayList<>(); //The highlighting of the product is that when the mouse moves to the word, the font changes color. This is the Map<String, Map<String, List<String>>> highlighting = response.getHighlighting(); for (SolrDocument solrDocument : documentList) { //Each SolrDocument is the content of a product pojo, so here we need to create a pojo object for the product to get the detailed field Item item=new Item(); item.setId((String) solrDocument.get("id")); // Highlighting is a title List<String> list = highlighting.get(solrDocument.get("id")).get("item_title"); String; if (list!=null && list.size()>0) { title=list.get(0); } else{ title=(String) solrDocument.get("item_title"); } item.setTitle(title); item.setPrice((Long) solrDocument.get("item_price")); item.setImage((String) solrDocument.get("item_image")); item.setCategory_name((String) solrDocument.get("item_category_name")); item.setSell_point((String) solrDocument.get("item_sell_point")); itemList.add(item); } result.setItemList(itemList); return result; } }Step 5: After the index library content is established, start writing an external service interface, that is, searching for specific products through conditions, such as mobile phones, will display a total mobile phone list information, which page, how many pages, and how many search results will be
Requested url:
/search/query?q={query conditions}&page={page}&rows={rows}
Returned result: TaotaoResult packaged product list.
Create a pojo corresponding to a sql statement, and create a pojo separately
List of contents used to install:
public class Item { private String id; private String title; private String sell_point; private long price; private String image; private String category_name; private String item_des; }Controller layer:
@Controllerpublic class SearchController { @Autowired private SearchService searchService; @RequestMapping(value="/query", method=RequestMethod.GET) @ResponseBody public TaotaoResult search(@RequestParam("q")String queryString, @RequestParam(defaultValue="1")Integer page, @RequestParam(defaultValue="60")Integer rows) { //The query condition cannot be empty if (StringUtils.isBlank(queryString)) { return TaotaoResult.build(400, "Query condition cannot be empty"); } SearchResult searchResult = null; try { queryString = new String(queryString.getBytes("iso8859-1"), "utf-8"); searchResult = searchService.search(queryString, page, rows); } catch (Exception e) { e.printStackTrace(); return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e)); } return TaotaoResult.ok(searchResult); } }<br><br><br>1<span style="font-size: 16px">service layer: use solrJ's solrQurery to query: </span>The prerequisite is to write how to read data from the index library:
The following is the interface layer of the service:
controller:
@Controllerpublic class SearchController { @Autowired private SearchService searchService; @RequestMapping(value="/query", method=RequestMethod.GET) @ResponseBody public TaotaoResult search(@RequestParam("q")String queryString, @RequestParam(defaultValue="1")Integer page, @RequestParam(defaultValue="60")Integer rows) { //The query condition cannot be empty if (StringUtils.isBlank(queryString)) { return TaotaoResult.build(400, "Query condition cannot be empty"); } SearchResult searchResult = null; try { queryString = new String(queryString.getBytes("iso8859-1"), "utf-8"); searchResult = searchService.search(queryString, page, rows); } catch (Exception e) { e.printStackTrace(); return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e)); } return TaotaoResult.ok(searchResult); } } @Servicepublic class SearchServiceImpl implements SearchService { @Autowired private SearchDao searchDao; @Override public SearchResult search(String queryString, int page, int rows) throws Exception { SolrQuery query=new SolrQuery(); query.setQuery(queryString); query.setStart((page-1)*rows); query.setRows(rows); //Set the default query search field, that is, the default query query.set("df","item_keywords"); //Set highlight query.setHighlight(true); query.addHighlightField("item_title"); query.setHighlightSimplePre("<em style=/"color:red/">"); query.setHighlightSimplePost("</em>"); //Execute the query SearchResult searchResult = searchDao.search(query); //Calculate how many pages of the product are long based on the results recordCount=searchResult.getRecordCount(); long pageCount=recordCount/rows; if (recordCount % rows > 0) { pageCount++; } searchResult.setPageCount(pageCount); searchResult.setCurPage((long) page); return searchResult; } }The client implements the search function by entering products:
Controller layer:
@Controller
public class SearchController { @Autowired private SearchService searchService; @RequestMapping("/search") public String search(@RequestParam("q")String queryString, @RequestParam(defaultValue="1")Integer page, Model model) { if (queryString != null) { try { queryString = new String(queryString.getBytes("iso8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } SearchResult searchResult = searchService.search(queryString, page); //Pass parameters model.addAttribute("query", queryString); //Model.addAttribute("totalPages", searchResult.getPageCount()); model.addAttribute("itemList", searchResult.getItemList()); model.addAttribute("page", page); return "search"; }}Service layer:
@Servicepublic class SearchServiceImpl implements SearchService { @Value("${SEARCH_BASE_URL}") private String SEARCH_BASE_URL; @Override public SearchResult search(String queryString, int page) { //What is needed here is the connection + parameter. The number of records displayed on each page can be passed or not // Call the service of taotao-search // Query parameters Map<String, String> param = new HashMap<>(); param.put("q", queryString); param.put("page", page + ""); try { //Calling the service String json = HttpClientUtil.doGet(SEARCH_BASE_URL, param); //Convert the string to a java object TaotaoResult taotaoResult = TaotaoResult.formatToPojo(json, SearchResult.class); SearchResult result = (SearchResult) taotaoResult.getData(); return result; /* if (taotaoResult.getStatus() == 200) { }*/ } catch (Exception e) { e.printStackTrace(); return null; } } }The above article using solr to realize product search function (example explanation) is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.