`
hui_jing_880210
  • 浏览: 42990 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Solr Suggestion 自动联想

    博客分类:
  • solr
阅读更多

修改core的solrconfig.xml

加入这段到<config />内

<searchComponent name="spellcheck" class="solr.SpellCheckComponent">
      <lst name="spellchecker">
        <str name="name">wordbreak</str>
        <str name="classname">org.apache.solr.spelling.suggest.Suggester</str>  
        <str name="lookupImpl">org.apache.solr.spelling.suggest.tst.TSTLookup</str>
        <str name="field">content</str>
        <str name="combineWords">true</str>
        <str name="breakWords">true</str>
        <int name="maxChanges">10</int>
      </lst>
    </searchComponent>
    <requestHandler name="/spellcheck" class="org.apache.solr.handler.component.SearchHandler">
      <lst name="defaults">
        <str name="spellcheck">true</str>
        <str name="spellcheck.dictionary">wordbreak</str>
        <str name="spellcheck.count">20</str>
      </lst>
      <arr name="last-components">
        <str>spellcheck</str>
      </arr>
    </requestHandler>

 schema.xml配置:

<?xml version="1.0" ?>
<schema name="my core" version="1.1">

    <fieldtype name="string"  class="solr.StrField" sortMissingLast="true" omitNorms="true"/>
    <fieldType name="long" class="solr.TrieLongField" precisionStep="0" positionIncrementGap="0"/>
    <fieldType name="tdate" class="solr.TrieDateField" precisionStep="6" positionIncrementGap="0"/>
    <fieldType name="int" class="solr.TrieIntField" precisionStep="0" positionIncrementGap="0"/>
    <fieldType name="float" class="solr.TrieFloatField" precisionStep="0" positionIncrementGap="0"/>
    <fieldType name="double" class="solr.TrieDoubleField" precisionStep="0" positionIncrementGap="0"/>
    <fieldType name="boolean" class="solr.BoolField" sortMissingLast="true"/>
    <fieldtype name="binary" class="solr.BinaryField"/>
    <fieldType name="text_cn" class="solr.TextField">
        <analyzer type="index" class="org.wltea.analyzer.lucene.IKAnalyzer" />
        <analyzer type="query" class="org.wltea.analyzer.lucene.IKAnalyzer" />
        <analyzer>
            <tokenizer class="solr.KeywordTokenizerFactory"/>
            <filter class="solr.LowerCaseFilterFactory"/>
        </analyzer>
    </fieldType>
    
    <!-- general -->
    <field name="id" type="long" indexed="true" stored="true" multiValued="false" required="true"/>
    <field name="subject" type="text_cn" indexed="true" stored="true" />
    <field name="content" type="text_cn" indexed="true" stored="true" />
    <field name="category_id" type="long" indexed="true" stored="true" />
    <field name="category_name" type="text_cn" indexed="true" stored="true" />
    <field name="last_update_time" type="tdate" indexed="true" stored="true" />
    <field name="_version_" type="long" indexed="true" stored="true"/>
    
     <!-- field to use to determine and enforce document uniqueness. -->
     <uniqueKey>id</uniqueKey>

     <!-- field for the QueryParser to use when an explicit fieldname is absent -->
     <defaultSearchField>subject</defaultSearchField>

     <!-- SolrQueryParser configuration: defaultOperator="AND|OR" -->
     <solrQueryParser defaultOperator="OR"/>
</schema>

关键在于这句:

 <analyzer>
            <tokenizer class="solr.KeywordTokenizerFactory"/>
            <filter class="solr.LowerCaseFilterFactory"/>
        </analyzer>

 意思是词组搜索

 

 

设置完xml,重启tomcat,在浏览器中运行:

http://localhost:8899/solr/mycore/spellcheck?spellcheck.build=true

运行结果:

 

然后在浏览器中运行:

http://localhost:8899/solr/mycore/spellcheck?q=中央&rows=0

运行结果:

 

java bean

package com.my.entity;

import java.util.Date;

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

public class Item {
    @Field
    private long id;
    @Field
    private String subject;
    @Field
    private String content;
    @Field("category_id")
    private long categoryId;
    @Field("category_name")
    private String categoryName;
    @Field("last_update_time")
    private Date lastUpdateTime;
    
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public long getCategoryId() {
        return categoryId;
    }
    public void setCategoryId(long categoryId) {
        this.categoryId = categoryId;
    }
    public String getCategoryName() {
        return categoryName;
    }
    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }
    public Date getLastUpdateTime() {
        return lastUpdateTime;
    }
    public void setLastUpdateTime(Date lastUpdateTime) {
        this.lastUpdateTime = lastUpdateTime;
    }
}

 

solrj 代码:

package com.my.solr;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

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 org.apache.solr.client.solrj.response.SpellCheckResponse;
import org.apache.solr.client.solrj.response.SpellCheckResponse.Collation;
import org.apache.solr.client.solrj.response.SpellCheckResponse.Correction;
import org.apache.solr.client.solrj.response.SpellCheckResponse.Suggestion;

import com.my.entity.Item;

public class TestSolr {

    public static void main(String[] args) throws IOException, SolrServerException {
        String url = "http://localhost:8899/solr/mycore";
        HttpSolrServer core = new HttpSolrServer(url);
        core.setMaxRetries(1);
        core.setConnectionTimeout(5000);
        core.setParser(new XMLResponseParser()); // binary parser is used by default
        core.setSoTimeout(1000); // socket read timeout
        core.setDefaultMaxConnectionsPerHost(100);
        core.setMaxTotalConnections(100);
        core.setFollowRedirects(false); // defaults to false
        core.setAllowCompression(true);

        // ------------------------------------------------------
        // remove all data
        // ------------------------------------------------------
        core.deleteByQuery("*:*");
        List<Item> items = new ArrayList<Item>();
        items.add(makeItem(1, "cpu", "this is intel cpu", 1, "cpu-intel"));
        items.add(makeItem(2, "cpu AMD", "this is AMD cpu", 2, "cpu-AMD"));
        items.add(makeItem(3, "cpu intel", "this is intel-I7 cpu", 1, "cpu-intel"));
        items.add(makeItem(4, "cpu AMD", "this is AMD 5000x cpu", 2, "cpu-AMD"));
        items.add(makeItem(5, "cpu intel I6", "this is intel-I6 cpu", 1, "cpu-intel-I6"));
        items.add(makeItem(6, "处理器", "中央处理器英特儿", 1, "cpu-intel"));
        items.add(makeItem(7, "处理器AMD", "中央处理器AMD", 2, "cpu-AMD"));
        items.add(makeItem(8, "中央处理器", "中央处理器Intel", 1, "cpu-intel"));
        items.add(makeItem(9, "中央空调格力", "格力中央空调", 3, "air"));
        items.add(makeItem(10, "中央空调海尔", "海尔中央空调", 3, "air"));
        items.add(makeItem(11, "中央空调美的", "美的中央空调", 3, "air"));
        core.addBeans(items);
        // commit
        core.commit();

        // ------------------------------------------------------
        // search
        // ------------------------------------------------------
        SolrQuery query = new SolrQuery();
        String token = "中央";
        query.set("qt", "/spellcheck");
        query.set("q", token);
        query.set("spellcheck", "on");
        query.set("spellcheck.build", "true");
        query.set("spellcheck.onlyMorePopular", "true");

        query.set("spellcheck.count", "100");
        query.set("spellcheck.alternativeTermCount", "4");
        query.set("spellcheck.onlyMorePopular", "true");

        query.set("spellcheck.extendedResults", "true");
        query.set("spellcheck.maxResultsForSuggest", "5");

        query.set("spellcheck.collate", "true");
        query.set("spellcheck.collateExtendedResults", "true");
        query.set("spellcheck.maxCollationTries", "5");
        query.set("spellcheck.maxCollations", "3");

        QueryResponse response = null;

        try {
            response = core.query(query);
            System.out.println("查询耗时:" + response.getQTime());
        } catch (SolrServerException e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
        } finally {
            core.shutdown();
        }

        SpellCheckResponse spellCheckResponse = response.getSpellCheckResponse();
        if (spellCheckResponse != null) {
            List<Suggestion> suggestionList = spellCheckResponse.getSuggestions();
            for (Suggestion suggestion : suggestionList) {
                System.out.println("Suggestions NumFound: " + suggestion.getNumFound());
                System.out.println("Token: " + suggestion.getToken());
                System.out.print("Suggested: ");
                List<String> suggestedWordList = suggestion.getAlternatives();
                for (String word : suggestedWordList) {
                    System.out.println(word + ", ");
                }
                System.out.println();
            }
            System.out.println();
            Map<String, Suggestion> suggestedMap = spellCheckResponse.getSuggestionMap();
            for (Map.Entry<String, Suggestion> entry : suggestedMap.entrySet()) {
                System.out.println("suggestionName: " + entry.getKey());
                Suggestion suggestion = entry.getValue();
                System.out.println("NumFound: " + suggestion.getNumFound());
                System.out.println("Token: " + suggestion.getToken());
                System.out.print("suggested: ");

                List<String> suggestedList = suggestion.getAlternatives();
                for (String suggestedWord : suggestedList) {
                    System.out.print(suggestedWord + ", ");
                }
                System.out.println("\n\n");
            }

            Suggestion suggestion = spellCheckResponse.getSuggestion(token);
            System.out.println("NumFound: " + suggestion.getNumFound());
            System.out.println("Token: " + suggestion.getToken());
            System.out.print("suggested: ");
            List<String> suggestedList = suggestion.getAlternatives();
            for (String suggestedWord : suggestedList) {
                System.out.print(suggestedWord + ", ");
            }
            System.out.println("\n\n");

            System.out.println("The First suggested word for solr is : " + spellCheckResponse.getFirstSuggestion(token));
            System.out.println("\n\n");

            List<Collation> collatedList = spellCheckResponse.getCollatedResults();
            if (collatedList != null) {
                for (Collation collation : collatedList) {
                    System.out.println("collated query String: " + collation.getCollationQueryString());
                    System.out.println("collation Num: " + collation.getNumberOfHits());
                    List<Correction> correctionList = collation.getMisspellingsAndCorrections();
                    for (Correction correction : correctionList) {
                        System.out.println("original: " + correction.getOriginal());
                        System.out.println("correction: " + correction.getCorrection());
                    }
                    System.out.println();
                }
            }
            System.out.println();
            System.out.println("The Collated word: " + spellCheckResponse.getCollatedResult());
            System.out.println();
        }

        System.out.println("查询耗时:" + response.getQTime());
    }

    private static Item makeItem(long id, String subject, String content, long categoryId, String categoryName) {
        Item item = new Item();
        item.setId(id);
        item.setSubject(subject);
        item.setContent(content);
        item.setLastUpdateTime(new Date());
        item.setCategoryId(categoryId);
        item.setCategoryName(categoryName);
        return item;
    }
}

 

测试结果:

 

分享到:
评论

相关推荐

    solr定时自动同步数据库需要用到的apache-solr-dataimportscheduler.jar包

    在标题提到的"solr定时自动同步数据库需要用到的apache-solr-dataimportscheduler.jar包"中,`apache-solr-dataimportscheduler.jar`是用于实现Solr数据导入计划任务的扩展插件。这个插件使我们能够设置定时任务,...

    solr搜索自动补全

    Solr搜索自动补全是现代电商网站常见的一项功能,它能够显著提升用户体验。当用户在搜索框输入关键词时,系统会根据输入的文字,实时展示一个下拉列表,该列表包含用户可能想要搜索的查询项。这不仅可以引导用户更快...

    solr注解自动扫描API

    用于扫描solr注解,solrJ调用创建实体类时,可用于导入该包接口API

    solr自动增量更新jar包

    solr自动增量更新jar包,适用于solr4的版本,希望对大家有帮助

    solr.war包solr.war包solr.war包solr.war包solr.war包

    solr.warsolr.war包solr.war包solr.war包solr.war包solr.war包solr.war包solr.war包solr.war包solr.war包solr.war包solr.war包solr.war包solr.war包solr.war包solr.war包solr.war包solr.war包solr.war包solr.war包...

    solr4.7服务搭建

    1. **启动 Tomcat**:启动 Tomcat 服务器,等待 Solr 战包自动部署。 2. **测试连接**:通过浏览器访问 `http://127.0.0.1:8080/solr/`,如果页面显示 Solr 的管理界面,则表示部署成功。 #### 九、中文分词技术...

    使用MySQL作为SOLR的索引源

    - **动态字段**:可以设置通配符动态字段,如`*_txt`,以自动匹配和处理MySQL中未预先定义的字段。 在实际应用中,为了提高性能,还可以考虑以下优化策略: - **索引优化**:对经常用于搜索的字段进行索引,减少...

    solr服务器_solr_

    安装Solr时,通常会将下载的Solr war文件放入Tomcat的webapps目录下,启动Tomcat后,Solr服务就会自动启动并提供访问接口。 总的来说,Solr服务器是企业级搜索引擎的重要选择,适用于电子商务、新闻门户、内部文档...

    solr_solr_

    Solr,全称为Apache Solr,是一款开源的企业级搜索平台,由Apache软件基金会维护。它基于Java,并且是Lucene库的一个高级搜索应用。Solr主要用于处理和索引大量文本数据,提供高效的全文检索、拼写检查、命中高亮、...

    solr(solr-9.0.0.tgz)

    然后可以通过POST请求将数据导入Solr,Solr会自动进行分词、建立倒排索引等操作,从而实现快速的全文检索。 Lucene是Solr的核心搜索引擎库,它提供了基本的搜索功能,如倒排索引、TF-IDF评分等。而Solr则在其基础上...

    solr

    除了基本的全文检索外,Solr还支持拼音搜索和自动补全等功能。例如,可以通过`SpellCheckResponse`类来获取拼写建议。 ```java SolrQuery spellcheckQuery = new SolrQuery("*:*"); spellcheckQuery.set Spellcheck...

    Apache Solr(solr-8.11.1.tgz)

    Apache Solr 是一个开源的全文搜索引擎,由Apache软件基金会维护,是Lucene项目的一部分。它提供了高效、可扩展的搜索和导航功能,广泛应用于企业级的搜索应用中。Solr-8.11.1是该软件的一个特定版本,包含了最新的...

    Solr全文检索.pdf

    6. Solr 的维护方式:Solr 的维护可以通过手动添加或使用 SpringDataSolr 来操作 Solr 索引库,第一次上线的时候可以手动往 Solr 索引库导入一批数据,后期可以自动更新。 7. 全文检索的实现:全文检索是由业务来定...

    solr-4.10.3

    在Solr-4.10.3中,这一特性已经相当成熟,支持自动分片、故障转移和负载均衡,使得Solr可以处理大规模的数据和高可用性需求。 2. **索引和查询**:Solr的核心功能在于构建高效的全文索引和执行复杂的查询。4.10.3...

    solr文档solr文档

    Solr,全称为Apache Solr,是一款开源的企业级搜索平台,由Apache软件基金会开发并维护。它是基于Lucene库的全文检索服务器,提供了高效的、可扩展的搜索和分析能力。Solr文档通常包含了关于如何安装、配置、优化...

    solr增量更新架包apache-solr-dataimportscheduler.jar

    "apache-solr-dataimportscheduler.jar" 是一个专门为Solr设计的扩展包,用于实现自动化的数据增量更新调度。 首先,我们要理解Solr的数据导入过程。Solr使用DataImportHandler(DIH)来从关系型数据库、XML文件或...

    solr-6.2.0源码

    Solr是Apache软件基金会开发的一款开源全文搜索引擎,它基于Java平台,是Lucene的一个扩展,提供了更为方便和强大的搜索功能。在Solr 6.2.0版本中,这个强大的分布式搜索引擎引入了许多新特性和改进,使其在处理大...

    solr搭建相关资源

    启动Tomcat,Solr会自动解压并部署。 4. 创建核心(Core):Solr中的每个独立索引被称为一个核心,你可以通过管理界面或者命令行工具创建新的核心,配置索引目录、数据源、分词器等参数。 5. 分词器配置:根据业务...

    solr-4.4.0.tgz

    如果你已经将 Solr 集成到 Tomcat,那么 Solr 会随着 Tomcat 的启动而自动启动。 5. **操作 Solr**: - 通过浏览器访问 `http://your_server:port/solr/admin` 来管理 Solr 实例,如创建、删除和配置核心。 - ...

    Apache Solr(solr-8.11.1.zip)

    它允许Solr集群进行自动故障转移和数据恢复,确保高可用性和容错性。 2. **集合与分片**:在SolrCloud中,数据被组织成“集合”,每个集合可以进一步划分为多个“分片”。分片有助于水平扩展,通过将数据分散在多台...

Global site tag (gtag.js) - Google Analytics