运行环境:
window7;jdk1.8;eclipse 之neno;tomcat7;solr 4;
1、安装solr在tomcat下;(见分类solr之数据库优化下的文章:window下安装solr到tomcat中:http://blog.youkuaiyun.com/happy_bigqiang/article/details/73195137)
2、考虑要使用solr查询的数据库字段,并把在solr的其中一个collection中设置域(同时设置中文分词器,这里id字段可以不设,因为solr配置文件schema.xml自动配置好了):
博主的schema.xml配置文件的路径在:
D:\ProgramFiles\solrhome\collection1\conf\schema.xml
在其中添加代码(注意这里不能写中文,包括注释,为了便于读者理解,博主写一些中文解释):
<!-- IKAnalyzer配置中文分词器-->
<fieldType name="text_ik" class="solr.TextField">
<analyzer class="org.wltea.analyzer.lucene.IKAnalyzer"/>
</fieldType>
<!-- com.taotao.search.solr Field这里博主要查五个字段,除去id字段还要配置四个,name可以随意命名,只要方便阅读即可-->
<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" />
<!-- 这里是复制域,是把四个域集中到一个域,方便solr查找-->
<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"/>
3、因为solr已经安装到tomcat中了,此时启动tomcat(博主是点击D:\ProgramFiles\apache-tomcat-7.0.76\bin\startup.bat)
4、在pom.xml中引入solr的客户端solrJ这个jar包,在工程中编写测试代码:TestSolrj.java,并运行(这里要注意因为博主使用的是maven工程构建,所以运行之前,要使用maven命令install这个工程,要不然用juint去运行会报找不到类的错误)
package com.taotao.solrJ;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Test;
public class TestSolrj {
@Test
public void testAddDocument ()throws Exception {
//创建一个SolrServer对象,创建一个HttpSolrServer对象
//需要指定Solr服务的url
//创建一个文档对象SolrInputDocument
//向文档中添加域,必须有id域,域的名称必须在scheme.xml中定义
//把文档对象写入索引库
//提交
//创建一个SolrServer对象,创建一个HttpSolrServer对象
//需要指定Solr服务的url
SolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr/collection1");
//创建一个文档对象SolrInputDocument
SolrInputDocument document = new SolrInputDocument();
//向文档中添加域,必须有id域,域的名称必须在scheme.xml中定义
document.addField("id","test04");
document.addField("item_title","测试商品1");
document.addField("item_price",100);
//把文档对象写入索引库
solrServer.add(document);
//提交
solrServer.commit();
}
}
5、在浏览器中输入http://localhost:8080/solr,进入solr自带的后台管理界面,选择collection1实例,点击query查询,就能发现测试代码中的已经建立,被查询出来了,bingo!!!
6、这里还未涉及如何将数据库中的自动,通过代码导入到solr中建立索引。