先说点废话。
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链接
- private static HttpSolrServer server;
- static {
- if (null == server) {
- //读取配置文件,初始化server
- Properties prop = new Properties();
- InputStream in = Solr.class.getResourceAsStream("/solr.properties");
- try {
- prop.load(in);
- server = new HttpSolrServer(prop.getProperty("baseUrl"));
- server.setConnectionTimeout(Integer.valueOf(prop .getProperty("connectionTimeout")));
- server.setDefaultMaxConnectionsPerHost(Integer.valueOf(prop .getProperty("defaultMaxConnectionsPerHost")));
- server.setMaxRetries(Integer.valueOf(prop .getProperty("maxRetries")));
- server.setMaxTotalConnections(Integer.valueOf(prop .getProperty("maxTotalConnections")));
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
2>>链接建立之后,就是写查询条件了,这是肯定的,就像你写sql语句一样,只是你要按照solr的语法写就是了
最终要的一个类就是SolrQuery这个类了API描述如下
- public class SolrQuery
- extends ModifiableSolrParams
- This is an augmented SolrParams with get/set/add fields for common fields used in the Standard and Dismax request handlers
构建查询语句
- SolrQuery query = new SolrQuery();
- query.setQuery("body_text:*** OR title_text:***");
- query.addField("***");
- query.setStart(0);
- query.setRows(10);
- query.addSortField("***", SolrQuery.ORDER.desc);
- query.addSortField("***", SolrQuery.ORDER.asc);
类似与这种查询语句,这都是最基本的一下solr的参数,可以参见 http://solrj.clucene.org/tech/34
最基本的就是这些了。下面来看下一些高级的使用,比如facet和groupby
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的方式,代码如下
- query.setFacet(true);
- query.addFacetField("manu")
这样就做成了一个最简单facet,最简单最简单的,调用之后,它就会给你返回一个xml格式的内容,你可以调用solrJ的API来取得相应的内容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
- addDateRangeFacet(String field, Date start, Date end, String gap)
- Add a numeric range facet.
这个也很重要的,java实例如下
- query.setFacet(true);
- query.addDateRangeFacet("date_dts", Calendar.getTime(), Calendar.getTime(), "+1DAY");
1DAY意思就是在start和endday之间按每天来分,使用的时候,需要注意
还有很多其他的method看看API,这非常重要
2..solrgroup by详解
你可能需要,先看一下wiki http://wiki.apache.org/solr/FieldCollapsing#Result_Grouping_.2BAC8_Field_Collapsing
使用的相关类:SolrServer、SolrQuery、QueryResponse、GroupResponse、GroupCommand、Group、SolrDocumentList
第一步,建立solr链接是肯定的,这个就不说了,
- SolrQuery params = new SolrQuery();
- params.set("q", "*:*");
- params.set("fq", "age:[20 TO 30]", "grade:[70 TO *]"); // filter query
- params.set("fl", "*,score"); // field list
- params.set("sort", "grade desc" ); //default score desc.
- params.set("start", "0");
- params.set("rows", "10");
- params.set("timeAllowed", "30000"); //miliseconds
- params.set("omitHeader", "true"); //default false
- params.set("cache", "false"); //default true
- //parameters only for grouping result
- params.set("group", "true");
- params.set("group.field", "id", "age");
- params.set("group.query", "学生", "学习", "grade:[0 TO 59.9]", "grade:[60 TO *]", "age:[10 TO 19]", "age:[20 TO *]" );
- //params.set("group.func", "grade GRATERTHAN 60"); // not found, don't use it!!!
- params.set("group.sort", "grade desc");
- params.set("group.format", "grouped"); //default:simple, other:grouped
- params.set("group.main", "false"); // when /*group.format=simple and */ group.main=true, just return the documentList only!!!
- params.set("group.ngroups", "true");
- params.set("group.truncate", "true"); //default is false;
- params.set("group.cache.percent", "50"); //default is 0;
- params.set("group.offset", "0");
- params.set("group.limit", "10");
然后取得查询结果
- QueryResponse response = null;
- try {
- response = solr.query(params);
- //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 {
- solr.shutdown();
- }
第三步:GroupResponse提供基于分组的查询结果:
获取GroupResponse:
GroupResponse groupResponse = response.getGroupResponse();
第四步
- if (response != null) {
- GroupResponse groupResponse = response.getGroupResponse();
- if (groupResponse != null) {
- List<GroupCommand> groupCommandList = groupResponse.getValues();
- for (GroupCommand groupCommand : groupCommandList) {
- System.out.println("GroupCommand Name : " + groupCommand.getName());
- System.out.println("Num of Groups Found: " + groupCommand.getNGroups());
- System.out.println("Num of documents Found: " + groupCommand.getMatches());
- System.out.println("The groups are: ");
- List<Group> groups = groupCommand.getValues();
- for (Group group : groups) {
- System.out.println("group value: " + group.getGroupValue());
- SolrDocumentList solrDocumentList = group.getResult();
- System.out.println("Num of Documents in this group: " + solrDocumentList.getNumFound());
- System.out.println("start: " + solrDocumentList.getStart());
- System.out.println("Max score: " + solrDocumentList.getMaxScore());
- // solrDocumentList.get(index)
- for (SolrDocument doc : solrDocumentList) {
- System.out.println("the Fields of document:");
- Collection<String> names = doc.getFieldNames();
- for (String name : names) {
- System.out.println(name + ": " + doc.getFieldValue(name));
- }
- System.out.println("\n");
- }
- System.out.println("\n\n");
- }
- System.out.println("\n\n");
- }
- }