流程
- tomcat+solr
- SSM
- SSM+(tomcat+solr)
工具版本
- tomcat:7.0.56
- solr:4.10.3
1.SSM+tomcat
解壓一個(gè)干凈的tomcat
-
修改tomcat中conf包下的tomcat-users.xml文件(tomcat有關(guān)用戶(hù)的配置)
- 在文件的中添加一下代碼(文件尾部有類(lèi)型內(nèi)容,被注釋掉了)
<role rolename="manager-gui"/> <role rolename="manager-script"/> <role rolename="manager-jmx"/> <role rolename="manager-status"/> <user username="yanm" password="yanm" roles="manager-gui, manager-script, manager-jmx, manager-status"/>
啟動(dòng)tomcat,輸入用戶(hù)名和密碼進(jìn)入管理界面,tomcat就完成了有關(guān)用戶(hù)的配置
- 進(jìn)入一下界面,就說(shuō)明用戶(hù)配置完成
將solr-dist-solr.war復(fù)制到tomcat-webapps下
重新啟動(dòng)tomcat
將solr-example-lib-ext下的所有包拷貝到tomcat-webapps-solr-WEB-INF-lib中
將solr-example-resource-log4j.properties復(fù)制到tomcat-webapps-solr-WEB-INF-classes下(classes是新建的,名字必須是這個(gè)名字)
新建solr_home文件夾,并將solr-example-solr-collection1(是整個(gè)文件下,不是文件夾下的內(nèi)容)復(fù)制到solr_home下
-
修改tomcat-webapps-solr-WEB-INF-web.xml文件(配置solr_home的位置)
- 解注其中的< env-entry>文件,并將solr_home的路徑修改
<env-entry> <env-entry-name>solr/home</env-entry-name> <env-entry-value>D:/Java/solr/solr2/solr_home</env-entry-value> <env-entry-type>java.lang.String</env-entry-type> </env-entry>
啟動(dòng)tomcat,訪(fǎng)問(wèn)
- 出現(xiàn)以下界面說(shuō)明,solr+tomcat已經(jīng)配置完成
-
安裝中文分詞器
-
配置 IKAnalyzer 的 jar 包
- 將solr安裝包下的IK Analyzer 2012FF_hf1包下 IKAnalyzer2012FF_u1.jar 拷?到 Tomcat 的webapps/solr/WEB-INF/lib 下。
-
IKAnalyzer 的配置?件
- 在 Tomcat的webapps/solr/WEB-INF/ 下創(chuàng)建 classes ?錄。(tomcat+solr時(shí) 已經(jīng)新建過(guò)了)
- 將 IKAnalyzer.cfg.xml胳搞、ext_stopword.dic 呢燥、mydict.dic copy 到 Tomcat的
webapps/solr/WEB-INF/classes
-
修改schema.xml文件(solr_home-collection1-conf下)
<fieldType name="text_ik" class="solr.TextField"> <analyzer class="org.wltea.analyzer.lucene.IKAnalyzer"/> </fieldType>
驗(yàn)證是否完成
-
2.搭建SSM項(xiàng)目
-
pom文件中添加依賴(lài)
<packaging>war</packaging> <properties> <!--統(tǒng)一管理spring所有的版本--> <spring-version>4.3.6.RELEASE</spring-version> </properties> <dependencies> <!--jsp--> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> <!--避免沖突--> </dependency> <!--servlet--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> <!--避免沖突--> </dependency> <!--jstl--> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--springmvc的依賴(lài)--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring-version}</version> </dependency> <!--rest風(fēng)格使用--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.10</version> </dependency> <!--mysql--> <!--<dependency> <groupId>org.mariadb.jdbc</groupId> <artifactId>mariadb-java-client</artifactId> <version>2.5.0</version> </dependency>--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.19</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.4</version> </dependency> <!--mybatis spring的插件块攒,將mybatis交給spring來(lái)管理--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency> <!--spring的單元測(cè)試--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring-version}</version> </dependency> <!--spring jdbc,包含事務(wù)--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring-version}</version> </dependency> <!-- spring aop的面向切面的配置--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.0</version> </dependency> <!--druid數(shù)據(jù)源--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.15</version> </dependency> <!--日志信息--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!--單元測(cè)試--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!--lombok,特別注意可柿,與maven的tomcat插件沖突時(shí)怯邪,將scope設(shè)置為provided--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.6</version> <scope>provided</scope> </dependency> <!--為了使用@Resource注解--> <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>1.3.2</version> </dependency> <!--solr依賴(lài)--> <dependency> <groupId>org.apache.solr</groupId> <artifactId>solr-solrj</artifactId> <version>4.10.3</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.1</version> </dependency> </dependencies> <build> <!--不過(guò)濾java下的xml文件--> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> <plugins> <!-- define the project compile level --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <!-- 添加tomcat插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <path>/</path> <port>80</port> </configuration> </plugin> </plugins> </build>
新建webapp包,并在包下新建WEB-INF包和index.html頁(yè)面
-
在WEB-INF包下新建web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!--配置springmvc--> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 使用springk框架寫(xiě)好的中文亂碼過(guò)濾器來(lái)實(shí)現(xiàn)亂碼的處理 --> <filter> <filter-name>encode</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encode</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
-
resource包下的db.properties文件
url=jdbc:mysql://localhost:3307/solr?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8 driver=com.mysql.cj.jdbc.Driver uname=root upass=root solr_server_url=http://localhost:8080/solr
-
resource包下的log4j.properties文件(使用log4j第三方日志包)
# 全局日志配置 # 共有四個(gè)級(jí)別 ERROE,DEBUG,WARN,INFO log4j.rootLogger=ERROR, stdout, F # MyBatis 日志配置,可以指定到包下,也可以指定到類(lèi)上,也可以指定到類(lèi)中的某一個(gè)方法 log4j.logger.com.yanm.dao.IUserDao=TRACE # 控制臺(tái)輸出 log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%6p [%t] - %m%n #打印到文件myproj.log中 log4j.appender.F = org.apache.log4j.DailyRollingFileAppender log4j.appender.F.File =myproj.log log4j.appender.F.Append = true log4j.appender.F.Threshold = ERROE log4j.appender.F.layout=org.apache.log4j.PatternLayout log4j.appender.F.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss}-[%p %F\:%L] %m%n
-
resource包下的spring-mvc.xml文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--設(shè)置ssm項(xiàng)目的注解配置--> <!--<context:annotation-config />--> <!--與下面的包掃描重復(fù)了--> <!--設(shè)置包掃描,分別掃描controller和service包--> <context:component-scan base-package="com.ym.controller"/> <context:component-scan base-package="com.ym.service" /> <!--注解驅(qū)動(dòng)--> <mvc:annotation-driven /> <!--配置默認(rèn)資源可以被訪(fǎng)問(wèn)--> <mvc:default-servlet-handler /> <!--引入spring和mybatis的整合文件--> <import resource="classpath:spring-mybatis.xml" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
-
resource包下的spring-mybatis.xml文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--引入數(shù)據(jù)庫(kù)的配置文件信息--> <context:property-placeholder location="classpath:db.properties" /> <!--druid數(shù)據(jù)源--> <bean id="ds" class="com.alibaba.druid.pool.DruidDataSource"> <property name="url" value="${url}" /> <property name="driverClassName" value="${driver}" /> <property name="username" value="${uname}" /> <property name="password" value="${upass}" /> </bean> <bean id="ssfb" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="typeAliasesPackage" value="com.ym.entity" /> <property name="mapperLocations" value="classpath*:dao/*Dao.xml" /> <property name="dataSource" ref="ds" /> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ym.dao" /> <property name="sqlSessionFactoryBeanName" value="ssfb"/> </bean> <!--配置事務(wù)管理器--> <bean id="dstm" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="ds"/> </bean> <!--聲明事務(wù)的實(shí)現(xiàn)方式 以這些關(guān)鍵字開(kāi)頭的方法分別設(shè)置事務(wù)的隔離級(jí)別以及出錯(cuò)后的操作--> <tx:advice id="tx" transaction-manager="dstm"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/> <tx:method name="insert*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/> <tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/> <tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="mpt" expression="execution(* com.ym.service.*.*(..))"/> <aop:advisor advice-ref="tx" pointcut-ref="mpt"/> </aop:config> <!--添加掃描,對(duì)service層進(jìn)行單元測(cè)試的時(shí)候,一定要定位到service包下--> <context:component-scan base-package="com.ym.service" /> </beans>
-
resource包下的mybatis-config.xml文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--給當(dāng)前mybatis項(xiàng)目添加日志功能绊寻,采用第三方日志jar包--> <settings> <setting name="logImpl" value="LOG4J"/> </settings> </configuration>
SSM項(xiàng)目搭建,可以寫(xiě)邏輯代碼了
-
entity層
- SolrData.java : 這是根據(jù)聯(lián)合查詢(xún)做的一個(gè)dto,應(yīng)該放到dto下,現(xiàn)先放在entity下
package com.ym.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; //寫(xiě)的是一個(gè)Dto,應(yīng)該放在dto包下,現(xiàn)在臨時(shí)放在entity下, @Data @AllArgsConstructor @NoArgsConstructor public class SolrData { private long id; private String title; private String sellPoint; private long price; private String image; private String catName; private String itemDesc; }
-
dao層接口
- SolrDataDao.java : 接口
package com.ym.dao; import com.ym.entity.SolrData; import java.util.List; public interface SolrDataDao { List<SolrData> getAllData(); }
-
與接口對(duì)應(yīng)的mapper文件
- SolrDataDao.xml : 使用聯(lián)合查詢(xún),返回結(jié)果映射成SolrData的類(lèi)型
<?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.ym.dao.SolrDataDao"> <select id="getAllData" resultType="SolrData"> SELECT i.id,i.title,i.sell_point sellPoint ,i.price,i.image,c.name catName,d.item_desc itemDesc FROM tb_item i, tb_item_cat c, tb_item_desc d WHERE i.cid=c.id AND i.id =d.item_id </select> </mapper>
-
service層接口及實(shí)現(xiàn)類(lèi)
- ISolrDataService : 接口
- SolrDataServiceImpl.java : 接口的實(shí)現(xiàn)類(lèi)
package com.ym.service; import com.ym.entity.SolrData; import java.util.List; public interface ISolrDataService { //查詢(xún)所有信息 List<SolrData> getAllData(); //判斷是否已經(jīng)寫(xiě)到solr中去了 boolean dataFromDB2Solr(); }
- 實(shí)現(xiàn)類(lèi)
package com.ym.service.impl; import com.ym.dao.SolrDataDao; import com.ym.entity.SolrData; import com.ym.service.ISolrDataService; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputField; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.io.IOException; import java.util.List; @Service public class SolrDataServiceImpl implements ISolrDataService { @Resource private SolrDataDao solrDataDao; @Value("${solr_server_url}") //@Value注解,就可以拿到db中的solr_server_url的值 private String baseURL; @Override public List<SolrData> getAllData() { List<SolrData> solrDatas = solrDataDao.getAllData(); return solrDatas; } @Override public boolean dataFromDB2Solr() { List<SolrData>list=getAllData(); //連接solr服務(wù)器 HttpSolrServer server=new HttpSolrServer(baseURL); //創(chuàng)建文檔對(duì)象 SolrInputDocument document=null; try { for (SolrData sd : list) { document=new SolrInputDocument(); //setField的name值一定要和schema.xml中的field中的值一定要相同,并且schema.xml中的field值不能重復(fù), // schema.xml中的field的值一定要和查詢(xún)的字段相對(duì)應(yīng),可以不一樣,但是一定要對(duì)應(yīng) document.setField("id",sd.getId()); document.setField("item_title",sd.getTitle()); document.setField("item_sell_point",sd.getSellPoint()); document.setField("item_price",sd.getPrice()); document.setField("item_image",sd.getImage()); document.setField("item_category_name",sd.getCatName()); document.setField("item_desc",sd.getItemDesc()); //向服務(wù)器中寫(xiě)入文檔 server.add(document); } //向服務(wù)器中提交 server.commit(); return true; } catch (SolrServerException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } }
-
controller層
- SolrDataController.java
package com.ym.controller; import com.ym.entity.SolrData; import com.ym.service.ISolrDataService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.List; @RestController public class SolrDataController { @Resource private ISolrDataService solrDataService; //測(cè)試能否獲取到內(nèi)容 @GetMapping("/solrData") public List<SolrData> getAllData(){ List<SolrData> datas = solrDataService.getAllData(); return datas; } @GetMapping("/dataFromDB2Solr") public boolean dataFromDB2Solr(){ return solrDataService.dataFromDB2Solr(); } }
3.SSM+(tomcat+solr)
-
修改scheme.xml文件(solr_home-collection1-conf下)
- 根據(jù)數(shù)據(jù)庫(kù)中查詢(xún)的字段添加field內(nèi)容,其中添加的field必須要和數(shù)據(jù)庫(kù)中的所要查詢(xún)的內(nèi)容對(duì)應(yīng),名字可以不一樣,但是一定要對(duì)應(yīng),service層用的document對(duì)象,向solr中添加查詢(xún)的內(nèi)容時(shí),也需要field中的這個(gè)name值
- service層實(shí)現(xiàn)類(lèi)setField的name值一定要和schema.xml中的field中的值一定要相同,并且schema.xml中的field值不能重復(fù),
<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"/> <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"/>
solr下的tomcat
啟動(dòng)SSM項(xiàng)目
請(qǐng)求SSM項(xiàng)目中的
/dataFromDB2Solr
請(qǐng)求訪(fǎng)問(wèn)solr下的tomcat驗(yàn)證是否配置完成
4.關(guān)鍵字查詢(xún),并使用分詞器,設(shè)置關(guān)鍵字高亮
- 此時(shí)是從solr服務(wù)器中取數(shù)據(jù),而不是從數(shù)據(jù)庫(kù)中查詢(xún)
- 修改SSM項(xiàng)目的代碼
-
service層接口及實(shí)現(xiàn)類(lèi)
- ISolrDataService : 接口
- SolrDataServiceImpl.java : 接口的實(shí)現(xiàn)類(lèi)
package com.ym.service; import com.ym.entity.SolrData; import java.util.List; public interface ISolrDataService { //從數(shù)據(jù)庫(kù)中找 List<SolrData> getAllData(); //將從從數(shù)據(jù)庫(kù)中查詢(xún)的內(nèi)容,保存到solr中 boolean dataFromDB2Solr(); //從solr中查找 List<SolrData> getAllDataFromSolr(String keyword); }
- 實(shí)現(xiàn)類(lèi)
package com.ym.service.impl; import com.ym.dao.SolrDataDao; import com.ym.entity.SolrData; import com.ym.service.ISolrDataService; import org.apache.commons.lang3.StringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputField; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; @Service public class SolrDataServiceImpl implements ISolrDataService { @Resource private SolrDataDao solrDataDao; /** * 通過(guò)value注解將db.properties文件中的solr_server_url注入給baseUrl */ @Value("${solr_server_url}") private String baseURL; //從數(shù)據(jù)庫(kù)中獲取查詢(xún)的內(nèi)容 @Override public List<SolrData> getAllData() { List<SolrData> solrDatas = solrDataDao.getAllData(); return solrDatas; } //將從數(shù)據(jù)庫(kù)中的內(nèi)容,保存到solr中 @Override public boolean dataFromDB2Solr() { List<SolrData>list=getAllData(); //連接solr服務(wù)器 HttpSolrServer server=new HttpSolrServer(baseURL); //創(chuàng)建文檔對(duì)象 SolrInputDocument document=null; try { for (SolrData sd : list) { document=new SolrInputDocument(); //setField的name值一定要和schema.xml中的field中的值一定要相同,并且schema.xml中的field值不能重復(fù), // schema.xml中的field的值一定要和查詢(xún)的字段相對(duì)應(yīng),可以不一樣,但是一定要對(duì)應(yīng) document.setField("id",sd.getId()); document.setField("item_title",sd.getTitle()); document.setField("item_sell_point",sd.getSellPoint()); document.setField("item_price",sd.getPrice()); document.setField("item_image",sd.getImage()); document.setField("item_category_name",sd.getCatName()); document.setField("item_desc",sd.getItemDesc()); //向服務(wù)器中寫(xiě)入文檔 server.add(document); } //向服務(wù)器中提交 server.commit(); return true; } catch (SolrServerException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } /** * Description: 在solr中查詢(xún)獲取內(nèi)容:根據(jù)關(guān)鍵字,包含分詞,高亮 * @author: YanM * @param: * @return: */ @Override public List<SolrData> getAllDataFromSolr(String keyword) { List<SolrData> solrDatas=null; //借助baseURL來(lái)創(chuàng)建一個(gè)httpSolrService對(duì)象 HttpSolrServer server=new HttpSolrServer(baseURL); //創(chuàng)建一個(gè)solrQuery對(duì)象 SolrQuery query=new SolrQuery(); try { //如果要檢索的關(guān)鍵字為空,則全查 if (StringUtils.isEmpty(keyword)){ query.setQuery("*:*"); }else { query.setQuery(keyword); } //設(shè)置df,默認(rèn)的查詢(xún)字段,在item_title上實(shí)現(xiàn)檢索 query.set("df","item_title"); //設(shè)置start的值,返回的結(jié)果的第幾條記錄開(kāi)始,一般分頁(yè)的時(shí)候使用,默認(rèn)從0開(kāi)始 query.set("start",0); //設(shè)置rows的值,值定返回結(jié)果最多多少條記錄,默認(rèn)是10,配合start實(shí)現(xiàn)分頁(yè) query.set("rows",30); //通過(guò)query對(duì)象的setHight(boolean)來(lái)設(shè)置查詢(xún)可高亮顯示 query.setHighlight(true); //開(kāi)啟高亮組件,或用query.setParam("hl","true") //設(shè)置高亮的域 query.addHighlightField("item_title"); //高亮字段 //設(shè)置高亮的前綴 query.setHighlightSimplePre("<font color='red'>");//標(biāo)記,高亮關(guān)鍵字前綴 //設(shè)置高亮的后綴 query.setHighlightSimplePost("</font>"); //標(biāo)記,高亮關(guān)鍵字后綴 //System.out.println(query); //使用之前創(chuàng)建的httpSolrService對(duì)象調(diào)用query(query)方法將query對(duì)象所設(shè)置的查詢(xún)條件加入進(jìn)來(lái)得到一個(gè)查詢(xún)響應(yīng)對(duì)象 QueryResponse response=server.query(query); //通過(guò)查詢(xún)響應(yīng)對(duì)象的getResult()方法的到SolrDocumentList對(duì)象 Map<String,Map<String,List<String>>> map=response.getHighlighting(); SolrDocumentList list = response.getResults(); if (list!=null&&list.size()!=0){ solrDatas=new ArrayList<>(); SolrData s=null; //遍歷得到的SolrDocumentList對(duì)象 for (SolrDocument sd : list) { s=new SolrData(); //SolrDocument對(duì)象的get(name)默認(rèn)返回值為object Object oid = sd.getFieldValue("id"); //將oid轉(zhuǎn)換為long類(lèi)型 long id=oid==null ?0:Long.parseLong((String)oid); s.setId(id); //通過(guò)高亮map對(duì)象設(shè)置solrData的title屬性 s.setTitle(map.get(sd.getFieldValue("id")).get("item_title").get(0)); Object oprice = sd.getFieldValue("item_price"); long price =oprice==null?0:((long) oprice); //設(shè)置價(jià)格 s.setPrice(price); //設(shè)置賣(mài)點(diǎn) s.setSellPoint((String)sd.getFieldValue("item_sell_point")); //設(shè)置圖片 s.setImage((String)sd.getFieldValue("item_image")); //設(shè)置商品種類(lèi)名稱(chēng) s.setCatName((String)sd.getFieldValue("item_category_name")); //設(shè)置條目描述 s.setItemDesc((String)sd.getFieldValue("item_desc")); //將solrData對(duì)象加入到列表中 solrDatas.add(s); } return solrDatas; } } catch (SolrServerException e) { e.printStackTrace(); } return null; } }
-
controller層
- SolrDataController.java
package com.ym.controller; import com.ym.entity.SolrData; import com.ym.service.ISolrDataService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.List; @Controller public class SolrDataController { @Resource private ISolrDataService solrDataService; //測(cè)試能否獲取到內(nèi)容 @GetMapping("/solrData") @ResponseBody public List<SolrData> getAllData(){ List<SolrData> datas = solrDataService.getAllData(); return datas; } //將從數(shù)據(jù)庫(kù)中的內(nèi)容,保存到solr服務(wù)器中 @GetMapping("/dataFromDB2Solr") @ResponseBody public boolean dataFromDB2Solr(){ return solrDataService.dataFromDB2Solr(); } //從solr中查找數(shù)據(jù)(rest風(fēng)格) @GetMapping("/getDataFromSolr") @ResponseBody public List<SolrData> getDataFromSolrByKeyWord(@RequestParam(value = "kw",defaultValue = "")String kw){ return solrDataService.getAllDataFromSolr(kw); } //從solr中查找數(shù)據(jù),并且返回到頁(yè)面 @PostMapping("/getDataFromSolrByKeyWord") public String searchPage(@RequestParam(value = "kw",defaultValue = "")String kw, Model model){ model.addAttribute("datas",solrDataService.getAllDataFromSolr(kw)); return "search"; } }
-
前端查詢(xún)頁(yè)面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>this is search page</h1> <form action="/getDataFromSolrByKeyWord" method="post"> KeyWard : <input type="text" name="kw"> <input type="submit" value="search"> </form> </body> </html>
-
前端查詢(xún)結(jié)果顯示
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>search</title> </head> <body> <h1>this is search detail</h1> <table border="1"> <tr> <th>id</th> <th>title</th> <th>sellPoint</th> <th>price</th> <th>image</th> <th>catName</th> <th>itemDesc</th> </tr> <c:forEach items="${datas}" var="s"> <tr> <td>${s.id}</td> <td>${s.title}</td> <td>${s.sellPoint}</td> <td>${s.price}</td> <td>${s.image}</td> <td>${s.catName}</td> <td>${s.itemDesc}</td> </tr> </c:forEach> </table> </body> </html>
-
過(guò)程演示
-
輸入"老人機(jī)",看查看結(jié)果
-
頁(yè)面顯示查詢(xún)結(jié)果
-