设为首页 收藏本站
查看: 1891|回复: 0

[经验分享] Solr API例子详解

[复制链接]

尚未签到

发表于 2016-3-7 08:30:29 | 显示全部楼层 |阅读模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
package test;

import java.io.IOException;  
import java.net.MalformedURLException;  
import java.text.SimpleDateFormat;
import java.util.ArrayList;  
import java.util.Date;
import java.util.List;   
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.util.CollectionUtil;
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.response.FacetField.Count;  
import org.apache.solr.client.solrj.response.QueryResponse;  
import org.apache.solr.common.SolrDocument;  
import org.apache.solr.common.SolrDocumentList;  
import org.apache.solr.common.SolrInputDocument;  
import org.junit.Test;  
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.tuke.gospel.core.vo.PaginationSupport;
import com.xd.iis.se.pojos.IContentCommon;
import com.xd.iis.se.pojos.SearchCondition;
import com.xd.intersys.actions.BaseAction;
import com.xd.intersys.ownutils.SolrWbFactory;
import com.xd.intersys.pojo.IContentCommonNet;
import com.xd.intersys.service.facadeImpl.ChartServiceImpl;
import com.xd.intersys.service.facadeImpl.QueryServiceImpl;  
@SuppressWarnings("deprecation")  
public class SolrTest {      
@Autowired
@Qualifier("queryService")
private QueryServiceImpl queryService;
@Autowired
@Qualifier("chartService")
private ChartServiceImpl chartService;

    //指定solr服务器的地址  
    private final static String URL = "http://192.168.20.195:8084/solr/comment";  

    @test  
    public void slorQuery() throws SolrServerException, MalformedURLException{  
        /*
         * //项目取得HttpSolrServer方式 HttpSolrServer
         * server=SolrWbFactory.getSolrServerComment();
         * weibo_comment_solr=http://192.168.20.195:8084/solr/comment
         * weibo_content_comment_solr=http://192.168.20.195:8084/solr/all
         * weibo_content_slor=http://192.168.20.195:8084/solr/collection1
         */
        HttpSolrServer server = new HttpSolrServer(URL);
        /*
         * server.setConnectionTimeout(180 * 1000); server.setSoTimeout(240 *
         * 1000); server.setMaxTotalConnections(1200);
         * server.setDefaultMaxConnectionsPerHost(100); server.setMaxRetries(3);
         * server.setAllowCompression(true);
         */
        // 定义查询字符串
        SolrQuery query = new SolrQuery("Content:*");

        // 设置查询关键字
        /* query.setQuery("Content:* AND Spare3:1 "); */
        // 指定查询返回字段
        /* query.setParam("fl", "Content,IndexTime"); */
        // 设置高亮
        query.setHighlight(true).setHighlightSimplePre("<span class='red'>")
                .setHighlightSimplePost("</span>");
        query.setParam("hl.fl", "Content");

        // 时间条件过滤
        /* query.addFilterQuery("Content:超哥"); */
        /*
         * query.addFilterQuery(
         * "Published:[1995-12-31T23:59:59.999Z TO 2016-03-06T00:00:00Z]");
         */
        query.addFilterQuery("Published:[* TO NOW]");
        // 实现分页的查询
        query.setStart(0);
        query.setRows(10);
        // 设定排序,如果需要对field进行排序就必须在schema.xml中对该field配置stored="true"属性
        query.addSort(IContentCommon.IndexField.Published.getName(),
                SolrQuery.ORDER.asc);

        QueryResponse res = server.query(query);
        // 查询出来的结果都保存在SolrDocumentList中
        SolrDocumentList sdl = res.getResults();
        System.out.println("总数:" + sdl.getNumFound());

        System.out.println(sdl.getMaxScore());
        for (SolrDocument sd : sdl) {

            String id = (String) sd.get("ID");
            // 打印高亮信息
            System.out.println(res.getHighlighting().get(id).get("Content"));
            //
            System.out.println(sd.get("ID") + "#" + sd.get("Content") + "#"
                    + sd.get("WeiboId") + "#" + sd.get("Published") + "#"
                    + sd.get("OriginType"));

            /* System.out.println(sd.getFieldValue("ID")); */
            Date date = (Date) sd.get("Published");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dstring = sdf.format(date);
            System.out.println(dstring);
        }

    }  



    @Test  
    public void condition() throws SolrServerException, MalformedURLException{  
        SearchCondition sc=new SearchCondition();
        sc.addFilter(null, null);
        sc.addHotsort(true, true);
        BaseAction baseAction=new BaseAction();
        sc=baseAction.getSearchCondition(null, null, 1, "", "", 1, "", 1,1, "", "", 1, "","");

        // QueryServiceImpl
        HttpSolrServer solrServer = SolrWbFactory.getSolrServerWb();
        // 通过Search得到SearchCondition
        SolrQuery query = queryService.getQuery(sc);
        /*
         * 实际调用的SearchCondition.toQuery方法lucene的query转换成slor的
         * 实际调用的getSearchBase(HttpSolrServer solrServer, SolrQuery query,
         * SearchCondition searchCondition, Integer page, Integer pagesize)
         * solrServer发送请求查询出来设置到IContentCommonNet对象中
         */

   PaginationSupport<IContentCommonNet> paginationSupport=queryService.getSearch(solrServer, query, sc, 1, 10);

        chartService.getWordCloud(paginationSupport, 300);

    }  


   /*
   java对象 <---> xml文件之间的转换
   JAXB注解JAXB能够使用Jackson对JAXB注解的支持实现(jackson-module-jaxb-annotations),既方便生成XML,也方便生成JSON
    @XmlRootElement對类标识自动转化类中有get 、set方法的属性,没有get、set方法的属性无法转化
    @XmlElement对属性标识,属性无需get、set方法

     public Analyzer analyzer = new IKAnalyzer(true);//true开启智能分词
         拿IKAnalyzer分词器为例,IKAnalyzer的切分方式是细粒度切分,当不需要智能处理时,
     其就把切出的所有词输出,但若启动了智能处理,那么接下来就是要进行消歧工作。
  智能分词结果:
    张三|说的|确实|在理
最细粒度分词结果:
    张三|三|说的|的确|的|确实|实在|在理

(1) TermAttribute: 表示token的字符串信息。比如"I'm"
(2) TypeAttribute: 表示token的类别信息(在上面讲到)。比如 I'm 就属于<APOSTROPHE>,有撇号的类型
(3) OffsetAttribute:表示token的首字母和尾字母在原文本中的位置。比如 I'm 的位置信息就是(0,3)
(4) PositionIncrementAttribute:这个有点特殊,它表示tokenStream中的当前token与前一个token在实际的原文本中相隔的词语数量。






  Math.round 四舍五入Math.round(1.4)=1  Math.round(1.5)=2  
  Math.ceil向上取整Math.ceil(1.4)=2.0  
  Math.floor向下取整



邮箱:yuanhai@miduchina.com

SVN账号密码
账号:yuanhai
密码:cmpz0cUx0p

hbase设置

hbase_server1=192.168.1.120
hbase_server2=192.168.1.121
hbase_server3=192.168.1.122

192.168.1.120 jintai-test-0
192.168.1.121 jintai-test-1
192.168.1.122 jintai-test-2

solr地址:http://192.168.20.195:8084/solr/#/

http://blog.csdn.net/zwx19921215/article/details/41820483

http://www.cnblogs.com/chenz/articles/3229997.html

http://blog.csdn.net/huoyunshen88/article/details/38082455

--------slor日期格式存储----------
TrieDateField  DateField 表示一个精确到毫秒的时间,值的格式是:
YYYY-MM-DD T hh:mm:ss Z

--------------来源类型-------------
BasicContent

-------字符串转换成日期工具类-----------------
DateUtilsIis.parse(strDate,strPattern)

------------错误码类型类-------------------
ErrorCodeConstant

//ArrayList线程安全
List<Map<String,Object>> data=Collections.synchronizedList(new ArrayList<Map<String,Object>>());


-------------监听器------------------
InitDataListener --> springmvc配置的监听器
01449763832357389257242


----------LinkedHashMap-----------
LinkedHashMap实体虽然是以Hash的顺序存放在Map的数组table里面,但是实体之间却用链表的形式保持了存入的先后关系。
LinkedHashMap保存了记录的插入顺序,所以当你需要输出的顺序和输入的相同,那么用LinkedHashMap可以实现,它还可以按读取顺序来排列。
Collections.sort方法对arraylist排序


    -------字段--------
    Spare3:微博的的层级
    Spare5:父微博的用户名
    CustomFlag1=1疑似负面
    CustomFlag1=2 负面
    CustomFlag1=3 敏感
    CustomFlag1=4 非敏感
    TitleHs 标题哈希   对于微博而言,标题就是内容

     UserScreenName 用户名
     ClusterContent   



    splitTypeFlg  xw和app默认不拆分,归到新闻里

    newlstSelect   1 为 模糊信息列表;2 表示精确信息列表
    select  =1 全部信息       对应着模糊搜索   newlstSelect=1

    *
    *
    */



    /**
     * 测试分组
    */
    @Test  
    public void facet() throws MalformedURLException, SolrServerException{  
        HttpSolrServer server = new HttpSolrServer(URL);
        SolrQuery query = new SolrQuery("*:*");
        query.setIncludeScore(false);
        query.setFacet(true);
        /* query.addFacetField("Province"); */
        query.addFacetField("Spare3");
        query.addFacetQuery("Spare3:[4 TO 7]");

        /*
         * FacetComponet有两种排序选择,分别是count和index,
         * count是按每个词出现的次数,index是按词的字典顺序。如果查询参数不指定facet.sort,solr默认是按count排序。
         */
        /* query.setFacetSort("index"); */
        query.setFacetSort("count");
        query.setFacetLimit(10);// 设置返回结果条数

        /* query.setFacetPrefix("湖");//设置前缀 */

        System.out.println(query.toString());

        QueryResponse res = server.query(query);
        /* List<Count> provinceList= res.getFacetField("Province").getValues(); */
        List<Count> spare3List = res.getFacetField("Spare3").getValues();

        /*
         * for(Count count : provinceList){
         * System.out.println(count.getName()+"#"+count.getCount());
         *
         * }
         */
        for (Count count : spare3List) {
            System.out.println(count.getName() + "#" + count.getCount());
        }

        // 得到FacetQuery结果
        Map<String, Integer> facetQueryResult = res.getFacetQuery();

        for (Map.Entry<String, Integer> fqr : facetQueryResult.entrySet()) {
            System.out.println(fqr.getKey() + ":" + fqr.getValue());
        }

        res.getFacetDate(null);
        res.getFacetDates();
        res.getFacetRanges();
        /**
         *
         *
         *
         * 控制台输出结果:
         *      
         *
            q=Usergender%3A*&fl=*&facet=true&facet.field=Spare3&facet.query=Spare3%3A%5B4+TO+7%5D&facet.sort=count&facet.limit=10
            0#35389
            4#22778
            3#22333
            2#16567
            1#15571
            6#13161
            5#12339
            7#11550
            8#2659
            9#1399
            Spare3:[4 TO 7]:59828

            ---------对应slor图形界面http访问url-----
            http://192.168.20.195:8084/solr/ ... ect?q=Usergender%3A*&
            wt=json&indent=true&facet=true&facet.query=Spare3%3A%5B4+TO+7%5D&facet.field=Spare3

            ---------------slor图形界面查询语法------------



             -------------- slor图形界面结果------------  


             "facet_counts": {
                "facet_queries": {
                  "Spare3:[4 TO 7]": 59828
                },
                "facet_fields": {
                  "Spare3": [
                    "0",
                    35389,
                    "4",
                    22778,
                    "3",
                    22333,
                    "2",
                    16567,
                    "1",
                    15571,
                    "6",
                    13161,
                    "5",
                    12339,
                    "7",
                    11550,
                    "8",
                    2659,
                    "9",
                    1399,
                    "10",
                    500,
                    "11",
                    187,
                    "12",
                    115,
                    "13",
                    51,
                    "14",
                    34,
                    "15",
                    30,
                    "16",
                    3
                  ]
                },
                "facet_dates": {},
                "facet_ranges": {}
              }



facet.range
http://…/select?&facet=true&facet.range=price&facet.range.start=5000&facet.range.end=8000&facet.range.gap=1000

solrconfig.xml配置
<requestHandler name="/browse" class="solr.SearchHandler" name="/select">
<lst name="defaults">
<str name="echoParams">explicit</str>
<int name="rows">10</int>
<str name="df">text</str>

str name="facet">on</str>
<str name="facet.range">Price</str>
<int name="f.Price.facet.range.start">0</int>
<int name="f.Price.facet.range.end">5000</int>
<int name="f.Price.facet.range.gap">1000</int>
</lst>
</requestHandler>

   facet.range节点中表示按范围分段的字段为Price
   f.Price.facet.range.start表示起始值为0
  f.Price.facet.range.end表示最大值为 5000
  f.Price.facet.range.gap表示每次间隔1000进行分段 ,
         */  



    }  



}



运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-187291-1-1.html 上篇帖子: windows下配置solr4.6.0服务器 下篇帖子: Solr配置中文分词器IKAnalyzer及增删改查调用
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表