solrj入门及进阶,高级使用

来源:互联网 发布:大连开发区知润山房照 编辑:程序博客网 时间:2024/05/16 06:15

先说点废话。

   Solr 是一个独立的企业级搜索应用服务器,它对外提供类似于 Web-service  API 接口。用户可以通过 http请求,向搜索引擎服务器提交一定格式的 XML 文件,生成索引;也可以通过 HttpGet 操作提出查找请求,并得到XML 格式的返回结果。这里主要讲解下通过 httpGet 请求这种方式。首先,我们就必须通过 HTTP 请求类似http://localhost:8989/solr/select?q=tags:t5AND t7&fl=auction_id&start=0&rows=4&sort=auction_iddesc,auction_point asc 的链接,对服务器进行访问。将最终结果以类似流的方式传回客户端。

  在 Solr 的连接请求,返回结果这一方面, Apache 已经为我们提供了 Solrj 这个工具,我们只需要简单的导入相关包,使用其简单的 API 就可以轻松对 solr 进行操作了。


1>>首先建立solrJ链接

[java] view plaincopy
  1. private static HttpSolrServer server;     
  2. static {  
  3.     if (null == server) {  
  4.             //读取配置文件,初始化server  
  5.             Properties prop = new Properties();  
  6.             InputStream in = Solr.class.getResourceAsStream("/solr.properties");  
  7.             try {  
  8.                     prop.load(in);  
  9.                     server = new HttpSolrServer(prop.getProperty("baseUrl"));  
  10.                     server.setConnectionTimeout(Integer.valueOf(prop .getProperty("connectionTimeout")));  
  11.                     server.setDefaultMaxConnectionsPerHost(Integer.valueOf(prop .getProperty("defaultMaxConnectionsPerHost")));  
  12.                     server.setMaxRetries(Integer.valueOf(prop .getProperty("maxRetries")));  
  13.                     server.setMaxTotalConnections(Integer.valueOf(prop .getProperty("maxTotalConnections")));  
  14.             } catch (IOException e) {  
  15.                     e.printStackTrace();  
  16.             }  
  17.     }  
  18. }  

2>>链接建立之后,就是写查询条件了,这是肯定的,就像你写sql语句一样,只是你要按照solr的语法写就是了

最终要的一个类就是SolrQuery这个类了API描述如下

[java] view plaincopy
  1. public class SolrQuery  
  2. extends ModifiableSolrParams  
  3. This is an augmented SolrParams with get/set/add fields for common fields used in the Standard and Dismax request handlers  

构建查询语句

[java] view plaincopy
  1. SolrQuery query = new SolrQuery();  
  2. query.setQuery("body_text:*** OR title_text:***");  
  3. query.addField("***");  
  4. query.setStart(0);  
  5. query.setRows(10);  
  6. query.addSortField("***", SolrQuery.ORDER.desc);  
  7. query.addSortField("***", SolrQuery.ORDER.asc);  

类似与这种查询语句,这都是最基本的一下solr的参数,可以参见 http://solrj.clucene.org/tech/34


最基本的就是这些了。下面来看下一些高级的使用,比如facetgroupby

1、先说facet

solr将以导航为目的的查询结果称为facet.它并不会修改查询结果信息,只是在查询结果上根据分类添加了count信息,然后用户根据count信息做进一步的查询,比如淘宝的查询列表中,上面会表示不同的类目相关查询结果的数量
比如搜索数码相机,在搜索结果栏会根据厂商,分辨率等维度列出,这里厂商,分辨率就是一个个facet. 
然后在厂商下面会有nikon,canon, sony等品牌,这个叫约束(constraints) 

接下来是根据选择,列出当前的导航路径,这个叫面包屑(breadcrumb). 
solr
有几种facet: 
普通facet,比如从厂商品牌的维度建立fact 
查询facet,比如根据价格查询时,将根据价格,设置多个区间,比如0-10,10-20, 20-30等 
日期facet,也是一种特殊的范围查询,比如按照月份进行facet. 

facet
的主要好处就是可以任意对搜索条件进行组合,避免无效搜索,改善搜索体验

facet
都是在查询时通过参数指定.比如 

httpapi中这样写

引用

"&facet=true&facet.field=manu"

使用solrJ时,java的方式,代码如下

[java] view plaincopy
  1. query.setFacet(true);  
  2. query.addFacetField("manu")  

这样就做成了一个最简单facet,最简单最简单的,调用之后,它就会给你返回一个xml格式的内容,你可以调用solrJAPI来取得相应的内容API的使用,可以参考http://solrj.clucene.org/tech/36

同样的facet的具体使用,你也可以参考http://wenku.baidu.com/view/1c3fd63143323968011c92cc.html 这篇文字,只是solrJ官方文档的补充,具体的应用,你还是需要很好的了解SolrQuery这个类,因为,基本所有的查询操作都是在这个类,及其基类上来实现的


在已有的查询基础上增加facetquery,可以这样写:

solrQuery.addFacetQuery("column:[* TO 10]")  

再推荐一篇文章http://blog.csdn.net/duck_genuine/article/details/6711590

[java] view plaincopy
  1. addDateRangeFacet(String field, Date start, Date end, String gap)  
  2.       Add a numeric range facet.  

这个也很重要的,java实例如下

[java] view plaincopy
  1. query.setFacet(true);  
  2. query.addDateRangeFacet("date_dts", Calendar.getTime(), Calendar.getTime(), "+1DAY");  

1DAY意思就是在startendday之间按每天来分,使用的时候,需要注意

还有很多其他的method看看API,这非常重要

2..solrgroup by详解

你可能需要,先看一下wiki http://wiki.apache.org/solr/FieldCollapsing#Result_Grouping_.2BAC8_Field_Collapsing

使用的相关类:SolrServerSolrQueryQueryResponseGroupResponseGroupCommandGroupSolrDocumentList

第一步,建立solr链接是肯定的,这个就不说了,

[java] view plaincopy
  1. SolrQuery params = new SolrQuery();  
  2. params.set("q""*:*");  
  3. params.set("fq""age:[20 TO 30]""grade:[70 TO *]"); // filter query  
  4. params.set("fl""*,score");  // field list  
  5. params.set("sort""grade desc" );  //default score desc.         
  6. params.set("start""0");  
  7. params.set("rows""10");  
  8. params.set("timeAllowed""30000"); //miliseconds  
  9. params.set("omitHeader""true"); //default false  
  10. params.set("cache""false");     //default true  
  11.   
  12. //parameters only for grouping result  
  13. params.set("group""true");          
  14. params.set("group.field""id""age");  
  15. params.set("group.query""学生""学习""grade:[0 TO 59.9]""grade:[60 TO *]""age:[10 TO 19]""age:[20 TO *]" );  
  16. //params.set("group.func", "grade GRATERTHAN 60"); // not found, don't use it!!!      
  17.   
  18. params.set("group.sort""grade desc");  
  19. params.set("group.format""grouped"); //default:simple, other:grouped  
  20. params.set("group.main""false");    // when /*group.format=simple and */ group.main=true, just return the documentList only!!!   
  21.   
  22. params.set("group.ngroups""true");  
  23. params.set("group.truncate""true"); //default is false;  
  24.   
  25. params.set("group.cache.percent""50"); //default is 0;  
  26.   
  27. params.set("group.offset""0");  
  28. params.set("group.limit""10");  


然后取得查询结果

[java] view plaincopy
  1. QueryResponse response = null;  
  2. try {  
  3.     response = solr.query(params);  
  4.     //System.out.println("查询耗时:" + response.getQTime());  
  5. catch (SolrServerException e) {  
  6.     System.err.println(e.getMessage());  
  7.     e.printStackTrace();  
  8. catch (Exception e) {  
  9.     System.err.println(e.getMessage());  
  10.     e.printStackTrace();  
  11. finally {  
  12.     solr.shutdown();  
  13. }  

第三步:GroupResponse提供基于分组的查询结果:

  获取GroupResponse

GroupResponse groupResponse = response.getGroupResponse();

       第四步

[java] view plaincopy
  1. if (response != null) {  
  2. GroupResponse groupResponse = response.getGroupResponse();  
  3.   
  4. if (groupResponse != null) {  
  5.     List<GroupCommand> groupCommandList = groupResponse.getValues();  
  6.     for (GroupCommand groupCommand : groupCommandList) {  
  7.     System.out.println("GroupCommand Name : " + groupCommand.getName());  
  8.     System.out.println("Num of Groups Found: " + groupCommand.getNGroups());  
  9.     System.out.println("Num of documents Found: " + groupCommand.getMatches());  
  10.   
  11.     System.out.println("The groups are: ");  
  12.     List<Group> groups = groupCommand.getValues();  
  13.     for (Group group : groups) {  
  14.             System.out.println("group value: " + group.getGroupValue());  
  15.             SolrDocumentList solrDocumentList = group.getResult();  
  16.             System.out.println("Num of Documents in this group: " + solrDocumentList.getNumFound());  
  17.             System.out.println("start: " + solrDocumentList.getStart());  
  18.             System.out.println("Max score: " + solrDocumentList.getMaxScore());  
  19.             // solrDocumentList.get(index)  
  20.       
  21.             for (SolrDocument doc : solrDocumentList) {  
  22.                     System.out.println("the Fields of document:");  
  23.                     Collection<String> names = doc.getFieldNames();  
  24.                     for (String name : names) {  
  25.                             System.out.println(name + ": " + doc.getFieldValue(name));  
  26.                     }  
  27.                     System.out.println("\n");  
  28.             }  
  29.             System.out.println("\n\n");  
  30.     }  
  31.     System.out.println("\n\n");  
  32.     }  
  33. }  
0 1
原创粉丝点击