Lucene和Solr-2

一.solr的下载和配置

  1.solr简介  

  Solr Apache下的一个顶级开源项目,采用Java开发,它是基于Lucene的全文搜索服务器。Solr提供了比Lucene更为丰富的查询语言,同时实现了可配置、可扩展,并对索引、搜索性能进行了优化。

  Solr可以独立运行,运行在JettyTomcat等这些Servlet容器中,Solr 索引的实现方法很简单,用 POST 方法向 Solr 服务器发送一个描述 Field 及其内容的 XML 文档,Solr根据xml文档添加、删除、更新索引 。Solr 搜索只需要发送 HTTP GET 请求,然后对 Solr 返回Xmljson等格式的查询结果进行解析,组织页面布局。Solr不提供构建UI的功能,Solr提供了一个管理界面,通过管理界面可以查询Solr的配置和运行情况。  

 

  2.solr的安装配置

    1.solr的下载   

  从Solr官方网站(http://lucene.apache.org/solr/ )下载Solr4.10.3,根据Solr的运行环境,Linux下需要下载lucene-4.10.3.tgzwindows下需要下载lucene-4.10.3.zip

 

Solr使用指南可参考:https://wiki.apache.org/solr/FrontPage。

 

    2.solr的文件夹目录

       

binsolr的运行脚本

contribsolr的一些贡献软件/插件,用于增强solr的功能。

dist:该目录包含build过程中产生的warjar文件,以及相关的依赖文件。

docssolrAPI文档

examplesolr工程的例子目录:

   example/solr:

  该目录是一个包含了默认配置信息的SolrCore目录。

  example/multicore

  该目录包含了在Solrmulticore中设置的多个Core目录。

  example/webapps:

      该目录中包括一个solr.war,该war可作为solr的运行实例工程。

licensessolr相关的一些许可信息

    3.solr的运行环境 

 

solr 需要运行在一个Servlet容器中,Solr4.10.3要求jdk使用1.7以上,Solr默认提供Jettyjava写的Servlet容器),本教程使用Tocmat作为Servlet容器,环境如下:

 

SolrSolr4.10.3

 

Jdkjdk1.7.0_72

 

Tomcatapache-tomcat-7.0.53

 

    4.solr整合tomcat

      

第一步:安装tomcatD:\temp\apache-tomcat-7.0.53

 

第二步:把solrwar包复制到tomcat webapp目录下。

 

\solr-4.10.3\dist\solr-4.10.3.war复制到D:\temp\apache-tomcat-7.0.53\webapps下。

 

改名为solr.war
第三步:solr.war解压。使用压缩工具解压或者启动tomcat自动解压。解压之后删除solr.war

 

第四步:把\solr-4.10.3\example\lib\ext目录下的所有的jar包添加到solr工程中

 

第五步:配置solrHomesolrCore

 

1)创建一个solrhome(存放solr所有配置文件的一个文件夹)。\solr-4.10.3\example\solr目录就是一个标准的solrhome

 

2)\solr-4.10.3\example\solr文件夹复制到D:\temp\0108路径下,改名为solrhome,改名不是必须的,是为了便于理解。

 

3)solrhome下有一个文件夹叫做collection1这就是一个solrcore。就是一个solr的实例。一个solrcore相当于mysql中一个数据库。Solrcore之间是相互隔离。

 

    1. solrcore中有一个文件夹叫做conf,包含了索引solr实例的配置信息。
    2. conf文件夹下有一个solrconfig.xml。配置实例的相关信息。如果使用默认配置可以不用做任何修改。

 

Xml的配置信息:

 

Libsolr服务依赖的扩展包,默认的路径是collection1\lib文件夹,如果没有  就创建一个

 

dataDir:配置了索引库的存放路径。默认路径是collection1\data文件夹,如 果没有data文件夹,会自动创建。

 

第六步:告诉solr服务器配置文件也就是solrHome的位置。修改web.xml使用jndi的方式告诉solr服务器。

 

Solr/home名称必须是固定的。

 

第七步:启动tomcat

 

第八步:访问http://localhost:8080/solr/

 

二.solr的后台管理.

  1.solr的后台页面

1.1.1. Dashboard

 

仪表盘,显示了该Solr实例开始启动运行的时间、版本、系统资源、jvm等信息。

 

1.1.2. Logging

 

Solr运行日志信息

 

1.1.3. Cloud

 

CloudSolrCloud,即Solr云(集群),当使用Solr Cloud模式运行时会显示此菜单,如下图是Solr Cloud的管理界面:

 

1.1.4. Core Admin

 

Solr Core的管理界面。Solr Core Solr的一个独立运行实例单位,它可以对外提供索引和搜索服务,一个Solr工程可以运行多个SolrCoreSolr实例),一个Core对应一个索引目录。

 

添加solrcore

 

第一步:复制collection1改名为collection2

 

第二步:修改core.propertiesname=collection2

 

第三步:重启tomcat

 

1.1.5. java properties

 

SolrJVM 运行环境中的属性信息,包括类路径、文件编码、jvm内存设置等信息。

 

1.1.6. Tread Dump

 

显示Solr Server中当前活跃线程信息,同时也可以跟踪线程运行栈信息。

 

1.1.7. Core selector

 

选择一个SolrCore进行详细操作,如下:

 

1.1.8. Analysis

 

通过此界面可以测试索引分析器和搜索分析器的执行情况。

 

1.1.9. Dataimport

 

可以定义数据导入处理器,从关系数据库将数据导入 Solr索引库中。

 

1.1.10. Document

 

通过此菜单可以创建索引、更新索引、删除索引等操作,界面如下:

 

/update表示更新索引,solr默认根据id(唯一约束)域来更新Document的内容,如果根据id值搜索不到id域则会执行添加操作,如果找到则更新。

 

1.1.11. Query

 

通过/select执行搜索索引,必须指定“q”查询条件方可搜索。

 

  2.solr的核心配置文件scheme.xml  

    schema.xml,在SolrCoreconf目录下,它是Solr数据表配置文件,它定义了加入索引的数据的数据类型的。主要包括FieldTypesFields和其他的一些缺省设置。

    

          2.1  FieldType域类型定义

 

 

 

下边text_general”是Solr默认提供的FieldType,通过它说明FieldType定义的内容:

 

<fieldType name="text_general" class="solr.TextField" positionIncrementGap="100">
      <analyzer type="index">
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />
        <!-- in this example, we will only use synonyms at query time
        <filter class="solr.SynonymFilterFactory" synonyms="index_synonyms.txt" ignoreCase="true" expand="false"/>
        -->
        <filter class="solr.LowerCaseFilterFactory"/>
      </analyzer>
      <analyzer type="query">
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />
        <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
        <filter class="solr.LowerCaseFilterFactory"/>
      </analyzer>
    </fieldType>

 

 

FieldType子结点包括:name,class,positionIncrementGap等一些参数:

 

name:是这个FieldType的名称

 

class:是Solr提供的包solr.TextFieldsolr.TextField 允许用户通过分析器来定制索引和查询,分析器包括一个分词器(tokenizer)和多个过滤器(filter

 

positionIncrementGap:可选属性,定义在同一个文档中此类型数据的空白间隔,避免短语匹配错误,此值相当于Lucene的短语查询设置slop值,根据经验设置为100

 

FieldType定义的时候最重要的就是定义这个类型的数据在建立索引和进行查询的时候要使用的分析器analyzer,包括分词和过滤

 

索引分析器中:使用solr.StandardTokenizerFactory标准分词器solr.StopFilterFactory停用词过滤器solr.LowerCaseFilterFactory小写过滤器。

 

搜索分析器中:使用solr.StandardTokenizerFactory标准分词器,solr.StopFilterFactory停用词过滤器,这里还用到了solr.SynonymFilterFactory同义词过滤器。

 

 

       2.3  Field定义

  

fields结点内定义具体的Fieldfiled定义包括name,type(为之前定义过的各种FieldType,indexed(是否被索引),stored(是否被储存),multiValued(是否存储多个值)等属性。

 

如下:

 

<field name="name" type="text_general" indexed="true" stored="true"/>

 

<field name="features" type="text_general" indexed="true" stored="true" multiValued="true"/>

 

multiValued:该Field如果要存储多个值时设置为truesolr允许一个Field存储多个值,比如存储一个用户的好友id(多个),商品的图片(多个,大图和小图),通过使用solr查询要看出返回给客户端是数组.

 

 

       2.4  uniqueKey

 

  Solr中默认定义唯一主键keyid域,如下:

 

 

<uniqueKey>id</uniqueKey>

       2.5 copyField复制域

 

<copyField source="cat" dest="text"/>
   <copyField source="name" dest="text"/>
   <copyField source="manu" dest="text"/>
   <copyField source="features" dest="text"/>
   <copyField source="includes" dest="text"/>
   <copyField source="manu" dest="manu_exact"/>

 

 

 

 

 

  copyField复制域,可以将多个Field复制到一个Field中,以便进行统一的检索:比如,输入关键字搜索title标题内容content

 

 

      2.6 dynamicField(动态字段)

 

  动态字段就是不用指定具体的名称,只要定义字段名称的规则,例如定义一个 dynamicFieldname *_i,定义它的typetext,那么在使用这个字段的时候,任何以_i结尾的字段都被认为是符合这个定义的,例如:name_igender_ischool_i等。

   <dynamicField name="*_i"  type="int"    indexed="true"  stored="true"/>
   <dynamicField name="*_is" type="int"    indexed="true"  stored="true"  multiValued="true"/>
   <dynamicField name="*_s"  type="string"  indexed="true"  stored="true" />
   <dynamicField name="*_ss" type="string"  indexed="true"  stored="true" multiValued="true"/>
   <dynamicField name="*_l"  type="long"   indexed="true"  stored="true"/>

 

 

 

 

 3.中文分词器的配置. 

 

第一步:把IKAnalyzer2012FF_u1.jar添加到solr/WEB-INF/lib目录下。

 

第二步:复制IKAnalyzer的配置文件和自定义词典和停用词词典到solrclasspath下。

 

第三步:在schema.xml中添加一个自定义的fieldType,使用中文分析器。 

 

第四步:定义field,指定fieldtype属性为text_ik

 

 

 

<!-- iKAnalyzer iK分词器-->
    <fieldType name="text_ik" class="solr.TextField">
        <analyzer class="org.wltea.analyzer.lucene.IKAnalyzer">
        </analyzer>
    </fieldType>
<!--定义需要的域-->
    <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_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"/>

 

 

 

三.管理索引库

  1.数据的批量导入.

 

使用dataimport插件批量导入数据。

 

第一步:把dataimport插件依赖的jar包添加到solrcorecollection1\lib)中

 

还需要mysql的数据库驱动。

 

第二步:配置solrconfig.xml文件,添加一个requestHandler

 

 <requestHandler name="/dataimport"

class="org.apache.solr.handler.dataimport.DataImportHandler">

    <lst name="defaults">

      <str name="config">data-config.xml</str>

     </lst>

  </requestHandler> 

 

第三步:创建一个data-config.xml,保存到collection1\conf\目录下

 

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

<dataConfig>   

<dataSource type="JdbcDataSource"   

  driver="com.mysql.jdbc.Driver"   

  url="jdbc:mysql://localhost:3306/lucene"   

  user="root"   

  password="root"/>   

<document>   

<entity name="product" query="SELECT pid,name,catalog_name,price,description,picture FROM products ">

 <field column="pid" name="id"/>

 <field column="name" name="product_name"/>

 <field column="catalog_name" name="product_catalog_name"/>

 <field column="price" name="product_price"/>

 <field column="description" name="product_description"/>

 <field column="picture" name="product_picture"/>

</entity>   

</document>   

 

</dataConfig>

    红色部分column要和数据库的列对应,name要和自定义的域对应.

 

第四步:重启tomcat

  2.索引的查询

 

q - 查询字符串,必须的,如果查询所有使用*:*

 

fq - filter query)过虑查询,作用:在q查询符合结果中同时是fq查询符合的,例如::

 

过滤查询价格从120的记录。

 

也可以在q”查询条件中使用product_price:[1 TO 20],如下:

 

也可以使用*”表示无限,例如:

 

20以上:product_price:[20 TO *]

 

20以下:product_price:[* TO 20]

 

sort - 排序,格式:sort=<field name>+<desc|asc>[,<field name>+<desc|asc>]… 。示例:

 

按价格降序

 

start - 分页显示使用,开始记录下标,从0开始rows - 指定返回结果最多有多少条记录,配合start来实现分页。

 

显示前10条。

 

fl - 指定返回那些字段内容,用逗号或空格分隔多个。

 

显示商品图片、商品名称、商品价格

 

df-指定一个搜索Field

 

也可以在SolrCore目录 中conf/solrconfig.xml文件中指定默认搜索Field,指定后就可以直接在“q”查询条件中输入关键字。

 

wt - (writer type)指定输出格式,可以有 xml, json, php, phps, 后面 solr 1.3增加的,要用通知我们,因为默认没有打开。

 

hl 是否高亮 ,设置高亮Field,设置格式前缀和后缀。

 

四.使用SolrJ客户端.

  1.什么是SolrJ    

  solrj是访问Solr服务的java客户端,提供索引和搜索的请求方法,SolrJ通常在嵌入在业务系统中,通过SolrJAPI接口操作Solr服务

 

 

  2.依赖的jar包

  

  3.添加文档.

第一步:创建一个java工程

 

第二步:导入jar包。包括solrJjar包。还需要

 

第三步:和Solr服务器建立连接。HttpSolrServer对象建立连接。

 

第四步:创建一个SolrInputDocument对象,然后添加域。

 

第五步:将SolrInputDocument添加到索引库。

 

第六步:提交。 

//向索引库中添加索引
    @Test
    public void addDocument() throws Exception {
        //和solr服务器创建连接
        //参数:solr服务器的地址
        SolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr");
        //创建一个文档对象
        SolrInputDocument document = new SolrInputDocument();
        //向文档中添加域
        //第一个参数:域的名称,域的名称必须是在schema.xml中定义的
        //第二个参数:域的值
        document.addField("id", "c0001");
        document.addField("title_ik", "使用solrJ添加的文档");
        document.addField("content_ik", "文档的内容");
        document.addField("product_name", "商品名称");
        //把document对象添加到索引库中
        solrServer.add(document);
        //提交修改
        solrServer.commit();
        
    }

 

 

 

  4.删除文档.  

   1.根据id删除

 

//删除文档,根据id删除
    @Test
    public void deleteDocumentByid() throws Exception {
        //创建连接
        SolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr");
        //根据id删除文档
        solrServer.deleteById("c0001");
        //提交修改
        solrServer.commit();
    }

 

 

 

   2.根据查询条件删除.查询条件完全支持Lucene的查询语法.

 

//根据查询条件删除文档
    @Test
    public void deleteDocumentByQuery() throws Exception {
        //创建连接
        SolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr");
        //根据查询条件删除文档
        solrServer.deleteByQuery("*:*");
        //提交修改
        solrServer.commit();
    }

 

 

 

  5.查询文档.

    1.简单查询

 

//查询索引
    @Test
    public void queryIndex() throws Exception {
        //创建连接
        SolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr");
        //创建一个query对象
        SolrQuery query = new SolrQuery();
        //设置查询条件
        query.setQuery("*:*");
        //执行查询
        QueryResponse queryResponse = solrServer.query(query);
        //取查询结果
        SolrDocumentList solrDocumentList = queryResponse.getResults();
        //共查询到商品数量
        System.out.println("共查询到商品数量:" + solrDocumentList.getNumFound());
        //遍历查询的结果
        for (SolrDocument solrDocument : solrDocumentList) {
            System.out.println(solrDocument.get("id"));
            System.out.println(solrDocument.get("product_name"));
            System.out.println(solrDocument.get("product_price"));
            System.out.println(solrDocument.get("product_catalog_name"));
            System.out.println(solrDocument.get("product_picture"));
            
        }
    }

 

 

 

    2.复杂查询

 

//复杂查询索引
    @Test
    public void queryIndex2() throws Exception {
        //创建连接
        SolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr");
        //创建一个query对象
        SolrQuery query = new SolrQuery();
        //设置查询条件
        query.setQuery("钻石");
        //过滤条件
        query.setFilterQueries("product_catalog_name:幽默杂货");
        //排序条件
        query.setSort("product_price", ORDER.asc);
        //分页处理
        query.setStart(0);
        query.setRows(10);
        //结果中域的列表
        query.setFields("id","product_name","product_price","product_catalog_name","product_picture");
        //设置默认搜索域
        query.set("df", "product_keywords");
        //高亮显示
        query.setHighlight(true);
        //高亮显示的域
        query.addHighlightField("product_name");
        //高亮显示的前缀
        query.setHighlightSimplePre("<em>");
        //高亮显示的后缀
        query.setHighlightSimplePost("</em>");
        //执行查询
        QueryResponse queryResponse = solrServer.query(query);
        //取查询结果
        SolrDocumentList solrDocumentList = queryResponse.getResults();
        //共查询到商品数量
        System.out.println("共查询到商品数量:" + solrDocumentList.getNumFound());
        //遍历查询的结果
        for (SolrDocument solrDocument : solrDocumentList) {
            System.out.println(solrDocument.get("id"));
            //取高亮显示
            String productName = "";
            Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
            List<String> list = highlighting.get(solrDocument.get("id")).get("product_name");
            //判断是否有高亮内容
            if (null != list) {
                productName = list.get(0);
            } else {
                productName = (String) solrDocument.get("product_name");
            }
            
            System.out.println(productName);
            System.out.println(solrDocument.get("product_price"));
            System.out.println(solrDocument.get("product_catalog_name"));
            System.out.println(solrDocument.get("product_picture"));
            
        }
    }

 

posted @ 2018-08-18 09:46  流浪的小蛤蟆  阅读(194)  评论(0)    收藏  举报