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

Solr Facet

    博客分类:
  • solr
 
阅读更多

1、在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="regionId" type="int" indexed="true" stored="true" />
    <field name="region" type="text_cn" indexed="true" stored="true" />
    <field name="categoryId" type="int" indexed="true" stored="true" />
    <field name="category" type="text_cn" indexed="true" stored="true" />
    <field name="price" type="float" 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>

2、Java bean:

package com.my.entity;
import org.apache.solr.client.solrj.beans.Field;
public class Item {
    @Field
    private long id;
    @Field
    private String subject;
    @Field
    private String content;
    @Field
    private int regionId;
    @Field
    private int categoryId;
    @Field
    private float price;
    
    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 int getRegionId() {
        return regionId;
    }
    public void setRegionId(int regionId) {
        this.regionId = regionId;
    }
    public int getCategoryId() {
        return categoryId;
    }
    public void setCategoryId(int categoryId) {
        this.categoryId = categoryId;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
}

3、使用solrj测试例子:

package com.my.solr;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrQuery.SortClause;
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.FacetField;
import org.apache.solr.client.solrj.response.FacetField.Count;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.params.FacetParams;
import com.my.entity.Item;

public class TestSolr {
    private static HashMap<Integer, String> mapRegion = new HashMap<Integer, String>();
    private static HashMap<Integer, String> mapCategory = new HashMap<Integer, String>();
    public static void main(String[] args) throws IOException,
            SolrServerException {
        // ------------------------------------------------------
        // Set map
        // ------------------------------------------------------
        mapRegion.put(1, "罗湖区");
        mapRegion.put(2, "南山区");
        mapRegion.put(3, "龙岗区");
        mapRegion.put(4, "福田区");
        mapCategory.put(1, "单间");
        mapCategory.put(2, "2房1厅");
        mapCategory.put(3, "3房2厅");
        mapCategory.put(4, "1房1厅");
        
        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(items.size() + 1, "龙城公寓一房一厅", "豪华城城公寓1房1厅,拧包入住", 1, 1, 1200f));
        items.add(makeItem(items.size() + 1, "兴新宿舍楼 1室0厅", " 中等装修 招女性合租", 1, 1, 1000f));
        items.add(makeItem(items.size() + 1, "西丽新屋村新宿舍楼单间", " 无敌装修只招女性", 2, 1, 1000f));
        items.add(makeItem(items.size() + 1, "大芬村信和爱琴居地铁口2房1厅", " 地铁口 + 出行便利=居家首选", 3, 2, 2000f));
        items.add(makeItem(items.size() + 1, "龙岗富豪花园3房2厅出租", " 离地铁口只要5分钟,快来秒杀吧", 3, 3, 4500f));
        items.add(makeItem(items.size() + 1, "海景房园3房2厅出租", "无敌海景,可以看到伦敦", 4, 3, 8500f));
        items.add(makeItem(items.size() + 1, "天域花园1房1厅出租", "男女不限,入住免水电一月", 2, 4, 1500f));
        items.add(makeItem(items.size() + 1, "神一样的漂亮,玉馨山庄3房2厅", "心动不如行动,拧包即可入住,来吧!", 1, 3, 9500f));
        items.add(makeItem(items.size() + 1, "玉馨山庄2房1厅,情侣最爱", "宅男宅女快来吧只要2500,走过路过,别再错过", 1, 2, 2500f));
        items.add(makeItem(items.size() + 1, "天域花园3房2厅出租", "都来看看,都来瞄瞄,3房只要7500.", 4, 3, 7500f));
        items.add(makeItem(items.size() + 1, "深都花园出租3房2厅", "找爱干净的人氏,全新装修", 4, 3, 5200f));
        core.addBeans(items);
        // commit
        core.commit();

        // ------------------------------------------------------
        // search
        // ------------------------------------------------------
        SolrQuery query = new SolrQuery();
        query.setQuery("*:*");
        query.setStart(0); // query的开始行数(分页使用)
        query.setRows(100); // query的返回行数(分页使用)
        query.setFacet(true); // 设置使用facet
        query.setFacetMinCount(1); // 设置facet最少的统计数量
        query.setFacetLimit(10); // facet结果的返回行数
        query.addFacetField("categoryId", "regionId"); // facet的字段
        query.setFacetSort(FacetParams.FACET_SORT_COUNT);
        query.addSort(new SortClause("id", ORDER.asc)); // 排序
        QueryResponse response = core.query(query);
        List<Item> items_rep = response.getBeans(Item.class);
        List<FacetField> facetFields = response.getFacetFields();
        // 因为上面的start和rows均设置为0,所以这里不会有query结果输出
        System.out.println("--------------------");
        System.out.println("Search result:");
        for (Item item : items_rep) {
            System.out.println("id=" + item.getId() + "\tsubject=" + item.getSubject()
                    + "\tregion=" + mapRegion.get(item.getRegionId())
                    + "\tcategory=" + mapCategory.get(item.getCategoryId())
                    + "\tprice=" + item.getPrice());
        }
        // 打印所有facet
        for (FacetField ff : facetFields) {
            System.out.println("--------------------");
            System.out.println("name=" + ff.getName() + "\tcount=" + ff.getValueCount());
            System.out.println("--------------------");
            switch (ff.getName()) {
            case "regionId":
                printOut(mapRegion, ff.getValues());
                break;
            case "categoryId":
                printOut(mapCategory, ff.getValues());
                break;
            }
        }
    }
    
    @SuppressWarnings({ "rawtypes" })
    private static void printOut(HashMap map, List<Count> counts) {
        for (Count count : counts) {
            System.out.println("name=" + map.get(Integer.parseInt(count.getName())) + "\tcount=" + count.getCount());
        }
        System.out.println("--------------------");
    }

    private static Item makeItem(long id, String subject, String content, int regionId, int categoryId, float price) {
        Item item = new Item();
        item.setId(id);
        item.setSubject(subject);
        item.setContent(content);
        item.setRegionId(regionId);
        item.setCategoryId(categoryId);
        item.setPrice(price);
        return item;
    }
}

 

 

运行结果:

 

如果把测试例子中的这句query:

query.setQuery("*:*");

修改为:

query.setQuery("subject:*出租* && price:[1000 TO 8000]");

运行结果将为:

如果将:

query.setFacetMinCount(1); // 设置facet最少的统计数量

修改为:

query.setFacetMinCount(0); // 设置facet最少的统计数量

运行结果为:

比较上面两个运行结果图可以看出,这个setFacetMinCount(...)方法是过滤将最少统计量的数据

当然,也可以使用solr admin的浏览器地址栏进行访问查询:

http://localhost:8899/solr/mycore/select?q=subject:*出租* AND price :[1000 TO 8000]&wt=json&indent=true&facet=true&facet.field=categoryId&facet.field=regionId&facet.sort=count

运行输出:

分享到:
评论

相关推荐

    solr facet 笔记

    solr facet 笔记

    solrj的facet查询总结

    Facet 查询是 Solr 的高级搜索功能之一,可以给用户提供更友好的搜索体验。在搜索关键字的同时,能够按照 Facet 的字段进行分组并统计。下面是对 SolrJ 的 Facet 查询的总结: 一、Facet 简介 Facet 是 Solr 的...

    Solr权威指南-上卷

    包括部署、配置、Solr Core、Solr DIH、全量导入、增量导入、索引、中文分词、查询组件、Solr Facet、高亮、查询建议,以及企业如何在真实的项目中使用Solr。不仅讲解了基本概念和使用方法,而且还分析了各组件的...

    Solr权威指南-下卷

    包括部署、配置、Solr Core、Solr DIH、全量导入、增量导入、索引、中文分词、查询组件、Solr Facet、高亮、查询建议,以及企业如何在真实的项目中使用Solr。不仅讲解了基本概念和使用方法,而且还分析了各组件的...

    Solr 搜索引擎 asp.net实现 示例详细操作步骤

    Solr是一个独立的企业级搜索应用服务器,它对外提供类似于Web-service的API接口。用户可以通过http请求,向搜索引擎服务器提交一定格式的XML文件,生成索引;也可以通过Http G Solr et操作提出查找请求,并得到XML...

    java进阶Solr从基础到实战

    在本套课程中,我们将全面的讲解Solr,从Solr基础到Solr高级,再到项目实战,基本上涵盖了Solr中所有的知识点。 主讲内容 章节一:Solr基础(上) 1. 环境搭建 2. 核心讲解 3. 数据导入 4. 各种中文分析器 章节二:...

    solr基础知识介绍

    3.2.2 Facet 3 3.3.3 Document 6 3.3.4 Field 6 3.3.5 IndexWriter 6 3.3.6 IndexSearcher 6 3.3.7 Directory 6 3.3.8 Segment 7 3.3.9 QueryParser 7 3.3.10 Hits 7 4.应用示例 7 4.1 创建索引 7 4.1 删除索引 7 ...

    Solr分组统计

    演示了怎样使用easysolr.net开发facet功能,怎样模糊查询,精确查询。

    solr查询语法.pdf

    排序 / 高亮 / facet / spellcheck:拼写检查 / spatial:空间搜索 / 检索运算符:

    Solr 入门资料

    Solr 入门资料 环境配置 facet

    multi-select-facet:Apache Solr,Vue和Go的多选方面示例

    博客文章:运行示例使用运行Solr。 $ make start-solr 或使用docker 。 $ PODMAN=docker make start-solr 运行API // build the api$ go build -v -o api// start the api with the initialization options$ ./api ...

    Go文本索引库Bleve.zip

    当使用 Java 和 JVM 的时候使用比较多的是 Lucene,Elasticsearch 和 Solr。但是有时候不想要那么多依赖,想要避免外部服务,简单编译部署就可以运行。所以 Couchbase 团队就构建了一个 Go 库,支持大部分 Lucene ...

    xmlfacets:基于 DjangoHaystack 的 xml 分面浏览应用程序

    在 Django-haystack 中可以使用多种搜索索引系统,例如 Solr 或 ElasticSearch。 安装 xmlfacets 需要 Python 2.7 和 PostgreSQL。 要设置本地开发环境,请安装 并确保您具有以下依赖项 libxml2 libxslt 可选:...

    navigator:Papyrologic Navigator的代码

    pn-dispatcher -Java servlet,用于持久性,检索和显示papyri.info记录曾经由pn-indexer,pn-mapping,pn-lemmas,pn-solr和pn-xslt文件处理过。 这里包含三个servlet: info.papyri.dispatch.browse....

Global site tag (gtag.js) - Google Analytics