SOLR

1.   Solr介绍

solr是一个外部的搜索应用服务器,开源的搜索平台,用于构建搜索应用程序,它建立在Lucene(全文搜索引擎)之上,solr还可以当成nosql服务器使用,优化搜索大量以文本为中心的数据。

2.   Solr安装及使用

1.下载压缩包,可以去官网:http://lucene.apache.org/solr/下载

2.把压缩包解压到一个路径中没有中文的目录下。

3.快速使用(使用solr默认的数据库),

a)      在solr目录下的example里有start.jar文件,在路径出输入cmd进入黑窗口

b)      在黑窗口里输入    java –jar start.jar    启动solr里的例子。没报错那基本启动成功了。黑窗口不能关(黑窗口相当于服务器像tomcat)。

 

c)      在浏览器里输入    127.0.0.1:8983/solr        进入solr,什么都不修改默认端口号就是8983,若进入则启动成功,没进入则启动失败。

 

d)      可以点击collection1进入数据库里

 

4.使用solr(自己创建)

a)      自己创建数据库模仿solr自带的数据库。看一下solr自带数据库结构。

 

 

 

 

b)      自己创建数据库名为taotao,看以上solr默认数据库来创建。

c)      先在example目录下创建taotao-solr文件夹,从solr把solr.xml复制到taotao-solr,不需要修改。

d)      在taotao-solr下创建数据库名的文件夹(taotao),在taotao里创建data文件夹、conf文件夹,从solr下collection1下复制core.properties属性文件,修改里面的name=taotao(这个是数据库名),在conf下collection1下conf下的schema.xml,solrconfig.xml复制到taotao-solr下taotao下conf下。两个都需要修改。

e)      修改schema.xml

<?xml version="1.0" encoding="UTF-8" ?>

<schema name="example" version="1.5">

  <!-- 必须保存的 -->

   <field name="_version_" type="long" indexed="true" stored="true"/>

  

   <field name="_root_" type="string" indexed="true" stored="false"/>

 <!-- field:设置数据库的字段

       name:字段名

       type:数据类型

       indexed:是否要索引,索引

       stored:是否要存储,

       required:是否要必须的,非空

 -->

   <field name="id" type="long" indexed="true" stored="true" required="true" multiValued="false" />

   <field name="title" type="string" indexed="true" stored="true" required="true" />

             

<!-- 设置id为唯一的 -->

 <uniqueKey>id</uniqueKey>

       <!-- fieldType:数据类型,上面属性的type只能写数据类型里的name -->

    <fieldType name="string" class="solr.StrField" sortMissingLast="true" />

    <fieldType name="boolean" class="solr.BoolField" sortMissingLast="true"/>

    <fieldType name="int" class="solr.TrieIntField" precisionStep="0" positionIncrementGap="0"/>

    <fieldType name="float" class="solr.TrieFloatField" precisionStep="0" positionIncrementGap="0"/>

    <fieldType name="long" class="solr.TrieLongField" precisionStep="0" positionIncrementGap="0"/>

    <fieldType name="double" class="solr.TrieDoubleField" precisionStep="0" positionIncrementGap="0"/>

    <fieldType name="tint" class="solr.TrieIntField" precisionStep="8" positionIncrementGap="0"/>

    <fieldType name="tfloat" class="solr.TrieFloatField" precisionStep="8" positionIncrementGap="0"/>

    <fieldType name="tlong" class="solr.TrieLongField" precisionStep="8" positionIncrementGap="0"/>

    <fieldType name="tdouble" class="solr.TrieDoubleField" precisionStep="8" positionIncrementGap="0"/>

    <fieldType name="date" class="solr.TrieDateField" precisionStep="0" positionIncrementGap="0"/>

</schema>

f)       修改solrconfig.xml,把<str name="df">text</str> 替换为<str name="df">title</str>,把<searchComponent name="elevator" class="solr.QueryElevationComponent" >整个标签注释掉,

3.solr在java使用

1.导入jar包

       <!-- solr -->

              <dependency>

                     <groupId>org.apache.solr</groupId>

                     <artifactId>solr-solrj</artifactId>

                     <version>4.10.2</version>

              </dependency>

              <!-- solr需要的日志文件 -->

              <dependency>

                     <groupId>commons-logging</groupId>

                     <artifactId>commons-logging</artifactId>

                     <version>1.1.1</version>

              </dependency>

              <dependency>

                     <groupId>org.apache.commons</groupId>

                     <artifactId>commons-lang3</artifactId>

                     <version>3.3.2</version>

              </dependency>

2.solr需要的对象

package com.solr.bean;

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

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown=true)//序列化时忽略不知道的属性

public class Item {

       @Field("id")//与schemal文件中的field name对照

       private Long id;

       @Field("title")

       private String title;

       @Field("sell_point")

       private String sellPoint;

       @Field("price")

       private Long price;

       @Field("num")

       private Integer num;

       private String barcode;

       @Field("image")

       private String image;

       private Integer cid;

       @Field("status")

       private Integer status;

       @Field("created")

       private Long created;

       @Field("update")

       private Long update;

       public Item() {

              super();

       }

       public Item(Long id, String title, String sellPoint, Long price, Integer num, String barcode, String image,

                     Integer cid, Integer status, Long created, Long update) {

              super();

              this.id = id;

              this.title = title;

              this.sellPoint = sellPoint;

              this.price = price;

              this.num = num;

              this.barcode = barcode;

              this.image = image;

              this.cid = cid;

              this.status = status;

              this.created = created;

              this.update = update;

       }

       public Long getId() {

              return id;

       }

       public void setId(Long id) {

              this.id = id;

       }

       public String getTitle() {

              return title;

       }

       public void setTitle(String title) {

              this.title = title;

       }

       public String getSellPoint() {

              return sellPoint;

       }

       public void setSellPoint(String sellPoint) {

              this.sellPoint = sellPoint;

       }

       public Long getPrice() {

              return price;

       }

       public void setPrice(Long price) {

              this.price = price;

       }

       public Integer getNum() {

              return num;

       }

       public void setNum(Integer num) {

              this.num = num;

       }

       public String getBarcode() {

              return barcode;

       }

       public void setBarcode(String barcode) {

              this.barcode = barcode;

       }

       public String getImage() {

              return image;

       }

       public void setImage(String image) {

              this.image = image;

       }

       public Integer getCid() {

              return cid;

       }

       public void setCid(Integer cid) {

              this.cid = cid;

       }

       public Integer getStatus() {

              return status;

       }

       public void setStatus(Integer status) {

              this.status = status;

       }

       public Long getCreated() {

              return created;

       }

       public void setCreated(Long created) {

              this.created = created;

       }

       public Long getUpdate() {

              return update;

       }

       public void setUpdate(Long update) {

              this.update = update;

       }

       @Override

       public String toString() {

              return "Item [id=" + id + ", title=" + title + ", sellPoint=" + sellPoint + ", price=" + price + ", num=" + num

                            + ", barcode=" + barcode + ", image=" + image + ", cid=" + cid + ", status=" + status + ", created="

                            + created + ", update=" + update + "]";

       }

      

}

3.测试使用solr的CRUD(需要开启solr服务器)

package com.solr.test;

import java.io.IOException;

import java.util.Date;

import java.util.List;

import java.util.Map;

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.impl.XMLResponseParser;

import org.apache.solr.client.solrj.response.QueryResponse;

import com.solr.bean.Item;

public class TestSolr {

       static HttpSolrServer httpSolrServer = null;

       public static void main(String[] args) {

              // 1.根据solr的地址创建httpSolrServer对象

              httpSolrServer = new HttpSolrServer("http://127.0.0.1:8983/taotao");

              // 2.设置

              httpSolrServer.setParser(new XMLResponseParser());// 设置以xml响应解析

              httpSolrServer.setMaxRetries(1);// 设置重连次数

              httpSolrServer.setConnectionTimeout(1000);// 设置允许超时时间,单位毫秒

              try {

                     select();

              } catch (SolrServerException e) {

                     e.printStackTrace();

              }

       }

       // 添加数据到solr里

       public static void insert() {

              Item item = new Item();

              item.setId(1L);

              item.setTitle("测试标题3");

              item.setSellPoint("测试卖点3");

              item.setStatus(1);

              item.setPrice(999L);

              item.setNum(98);

              item.setCreated(new Date().getTime());

              item.setUpdate(item.getCreated());

             

              try {

                     httpSolrServer.addBean(item);//添加对象

                     httpSolrServer.commit();//提交事物

              } catch (IOException e) {

                     e.printStackTrace();

              } catch (SolrServerException e) {

                     e.printStackTrace();

              }

       }

      

       // 更新数据到solr里

       public static void update() {

              Item item = new Item();

              item.setId(1L);

              item.setTitle("测试标题2");

              item.setSellPoint("测试卖点3");

              item.setStatus(1);

              item.setPrice(999L);

              item.setNum(98);

              item.setCreated(new Date().getTime());

              item.setUpdate(item.getCreated());

             

              try {

                     httpSolrServer.addBean(item);//添加对象

                     httpSolrServer.commit();//提交事物

              } catch (IOException e) {

                     e.printStackTrace();

              } catch (SolrServerException e) {

                     e.printStackTrace();

              }

       }

      

       //删除solr里数据

       public static void delete() {

              try {

                     httpSolrServer.deleteById("1");//根据id删除

                     httpSolrServer.commit();//提交事物

              } catch (SolrServerException e) {

                     e.printStackTrace();

              } catch (IOException e) {

                     e.printStackTrace();

              }

       }

      

       //查询solr数据

       public static void select() throws SolrServerException {

              int page=1;

              int rows=2;

              String keywords="手机";

              SolrQuery solrQuery=new SolrQuery();

              solrQuery.setQuery("title:"+keywords+" AND status:1");

             

              solrQuery.setStart((Math.max(page, 1)-1)*rows);

              solrQuery.setRows(rows);

             

              //是否需要高亮

              boolean isHigjLighting=!StringUtils.equals("*", keywords)&&StringUtils.isNotBlank(keywords);

              if(isHigjLighting) {

                     solrQuery.setHighlight(true);//开启高亮

                     solrQuery.addHighlightField("title");//高亮字段

                     solrQuery.setHighlightSimplePre("<em>");

                     solrQuery.setHighlightSimplePost("</em>");

              }

             

              //执行查询

              QueryResponse queryResponse=httpSolrServer.query(solrQuery);

              List<Item> items=queryResponse.getBeans(Item.class);

              if(isHigjLighting) {

                     Map<String, Map<String, List<String>>> map=queryResponse.getHighlighting();

                     for(Map.Entry<String, Map<String, List<String>>> highlighting:map.entrySet()) {

                            for(Item item:items) {

                                   if(highlighting.getKey().equals(item.getId().toString())) {

                                          continue;

                                   }

                                   item.setTitle(StringUtils.join(highlighting.getValue().get("title"),""));

                                   break;

                            }

                     }

                    

              }

             

              for(Item item:items) {

                     System.out.println(item);

              }

             

       }

}

4.   solr和spring整合

<?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"

       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-4.1.xsd">

       <!-- solr和spring的整合 -->

      

       <!-- 创建httpSolrServer -->

       <bean id="httpSolrServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer">

              <constructor-arg index="0" value="http://127.0.0.1:8983/taotao"/>

              <property name="parser">

                     <bean class="org.apache.solr.client.solrj.impl.XMLResponseParser">

                     </bean>

              </property>

              <!--

                     maxRetries:最大重连次数

                     connectionTimeout:连接时长

               -->

              <property name="maxRetries" value="1"/>

              <property name="connectionTimeout" value="5000"/>

       </bean>

</beans>

原文地址:https://www.cnblogs.com/kfsrex/p/11853627.html