Solrj是Solr搜索服务器的一个比较基础的客户端工具,可以非常方便地与Solr搜索服务器进行交互。最基本的功能就是管理Solr索引,包括添加、更新、删除和查询等。对于一些比较基础的应用,用Solj基本够用,而且你可以非常容易地通过使用Solrj的API实现与Solr搜索服务器进行交互,实现对Solr的基本管理功能。如果你的应用比较复杂,可以扩展Solrj来满足需要。

Solrj是Solr搜索服务器的一个比较基础的客户端工具,可以非常方便地与Solr搜索服务器进行交互。最基本的功能就是管理Solr索引,包括添加、更新、删除和查询等。对于一些比较基础的应用,用Solj基本够用,而且你可以非常容易地通过使用Solrj的API实现与Solr搜索服务器进行交互,实现对Solr的基本管理功能。如果你的应用比较复杂,可以扩展Solrj来满足需要。

使用 SolrJ操作索引库:

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
package com.hcm.solr.test;
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.junit.Before;
import org.junit.Test;
 
import com.hcm.solr.entity.Message;
 
public class SolrTest {
 
    private static Log logger = LogFactory.getLog(SolrTest.class);
 
    private static final String URL = "http://127.0.0.1:8086/solr";
 
    private HttpSolrServer server = null;
 
    @Before
    public void init() {
        // 创建 server
        server = new HttpSolrServer(URL);
    }
 
    /**
     * 添加文档
     */
    @Test
    public void addDoc() {
 
        SolrInputDocument doc = new SolrInputDocument();
 
        doc.addField("id", "11");
        doc.addField("title", "this is my document !!");
 
        try {
 
            UpdateResponse response = server.add(doc);
            // 提交
            server.commit();
 
            logger.info("########## Query Time :" + response.getQTime());
            logger.info("########## Elapsed Time :" + response.getElapsedTime());
            logger.info("########## Status :" + response.getStatus());
 
        } catch (SolrServerException | IOException e) {
            logger.error("", e);
        }
    }
 
    /**
     * 添加多个文档
     */
    @Test
    public void addDocs() {
 
        String[] titles = new String[] { "aaaaaaa", "bbbbbbb", "ccccccc", "dddddd", "eeeeee" };
 
        List<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
 
        int i = 0;
        for (String str : titles) {
            SolrInputDocument doc = new SolrInputDocument();
            doc.addField("id", i++);
            doc.addField("title", str);
            docs.add(doc);
        }
 
        try {
 
            UpdateResponse response = server.add(docs);
            server.commit();
 
            logger.info("########## Query Time :" + response.getQTime());
            logger.info("########## Elapsed Time :" + response.getElapsedTime());
            logger.info("########## Status :" + response.getStatus());
 
        } catch (SolrServerException | IOException e) {
            logger.error("", e);
        }
    }
 
    /**
     * 添加一个Entity到索引库
     */
    @Test
    public void addBean() {
 
        Message msg = new Message("1001", "What is Fluentd?", new String[] { "Fluentd is an open source data collector for unified logging layer",
                "Fluentd allows you to unify data collection and consumption for a better use and understanding of data.",
                "Fluentd decouples data sources from backend systems by providing a unified logging layer in between.",
                "Fluentd proves you can achieve programmer happiness and performance at the same time. A great example of Ruby beyond the Web.",
                "Fluentd to differentiate their products with better use of data." });
 
        try {
 
            UpdateResponse response = server.addBean(msg);
            server.commit();
 
            logger.info("########## Query Time :" + response.getQTime());
            logger.info("########## Elapsed Time :" + response.getElapsedTime());
            logger.info("########## Status :" + response.getStatus());
 
        } catch (SolrServerException | IOException e) {
            logger.error("", e);
        }
    }
 
    /**
     * 添加多个Entity到索引库
     */
    @Test
    public void addBeans() {
 
        List<Message> msgs = new ArrayList<Message>();
 
        Message msg = new Message("1001", "What is Fluentd?", new String[] { "Fluentd is an open source data collector for unified logging layer",
                "Fluentd allows you to unify data collection and consumption for a better use and understanding of data.",
                "Fluentd decouples data sources from backend systems by providing a unified logging layer in between.",
                "Fluentd proves you can achieve programmer happiness and performance at the same time. A great example of Ruby beyond the Web.",
                "Fluentd to differentiate their products with better use of data." });
 
        Message msg2 = new Message("1002", "What is Fluentd?", new String[] { "Fluentd is an open source data collector for unified logging layer",
                "Fluentd allows you to unify data collection and consumption for a better use and understanding of data.",
                "Fluentd decouples data sources from backend systems by providing a unified logging layer in between.",
                "Fluentd proves you can achieve programmer happiness and performance at the same time. A great example of Ruby beyond the Web.",
                "Fluentd to differentiate their products with better use of data." });
 
        msgs.add(msg);
        msgs.add(msg2);
 
        try {
 
            UpdateResponse response = server.addBeans(msgs);
            server.commit();
 
            logger.info("########## Query Time :" + response.getQTime());
            logger.info("########## Elapsed Time :" + response.getElapsedTime());
            logger.info("########## Status :" + response.getStatus());
 
        } catch (SolrServerException | IOException e) {
            logger.error("", e);
        }
    }
 
    /**
     * 删除索引
     */
    @Test
    public void deleteDoc() {
        try {
            server.deleteById("0");
            server.commit();
        } catch (SolrServerException | IOException e) {
            logger.error("", e);
        }
    }
     
    /**
     * 更新索引<br>
     * solr索引库不同于数据库,没有更新的功能。如果想更新,先通过id删除对应的文档,再添加新的文档。
     */
    @Test
    public void updateDoc() {
        // ... ...
    }
 
    /**
     * 查询
     */
    @Test
    public void testQuery() {
        String queryStr = "*:*";
        SolrQuery params = new SolrQuery(queryStr);
        params.set("rows", 10);
        try {
            QueryResponse response = server.query(params);
            SolrDocumentList list = response.getResults();
            logger.info("########### 总共 : " + list.getNumFound() + "条记录");
            for (SolrDocument doc : list) {
                logger.info("######### id : " + doc.get("id") + "  title : " + doc.get("title"));
            }
        } catch (SolrServerException e) {
            logger.error("", e);
        }
    }
 
    /**
     * 简单查询(分页)
     */
    @Test
    public void querySimple() {
        ModifiableSolrParams params = new ModifiableSolrParams();
        params.set("q", "this my");
        params.set("q.op", "and");
        params.set("start", 0);
        params.set("rows", 5);
        params.set("fl", "*,score");
        try {
            QueryResponse response = server.query(params);
            SolrDocumentList list = response.getResults();
            logger.info("########### 总共 : " + list.getNumFound() + "条记录");
            for (SolrDocument doc : list) {
                logger.info("######### id : " + doc.get("id") + "  title : " + doc.get("title"));
            }
        } catch (SolrServerException e) {
            logger.error("", e);
        }
    }
 
    /**
     * 查询(分页,高亮)
     */
    @Test
    public void queryCase() {
        String queryStr = "title:this";
        SolrQuery params = new SolrQuery(queryStr);
        params.set("start", 0);
        params.set("rows", 5);
 
        // 启用高亮组件, 设置高亮
        params.setHighlight(true)                          
            .addHighlightField("title")                    
            .setHighlightSimplePre("<span class=\"red\">")
            .setHighlightSimplePost("</span>")
            .setHighlightSnippets(2)
            .setHighlightFragsize(1000)
            .setStart(0)
            .setRows(10)
            .set("hl.useFastVectorHighlighter", "true")
            .set("hl.fragsize", "200");
 
        try {
            QueryResponse response = server.query(params);
            SolrDocumentList list = response.getResults();
            logger.info("########### 总共 : " + list.getNumFound() + "条记录");
            for (SolrDocument doc : list) {
                logger.info("######### id : " + doc.get("id") + "  title : " + doc.get("title"));
            }
 
            Map<String, Map<String, List<String>>> map = response.getHighlighting();
            Iterator<String> iterator = map.keySet().iterator();
 
            while (iterator.hasNext()) {
                String key = iterator.next();
                Map<String, List<String>> values = map.get(key);
                logger.info("############################################################");
                logger.info("############ id : " + key);
 
                for (Map.Entry<String, List<String>> entry : values.entrySet()) {
                    String subKey = entry.getKey();
                    List<String> subValues = entry.getValue();
 
                    logger.info("############ subKey : " + subKey);
                    for (String str : subValues) {
                        logger.info("############ subValues : " + str);
                    }
                }
                 
            }
             
        } catch (SolrServerException e) {
            logger.error("", e);
        }
    }
 
}

POJO:

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
package com.hcm.solr.entity;
 
import java.io.Serializable;
 
import org.apache.solr.client.solrj.beans.Field;
 
public class Message implements Serializable {
 
    /**
     *
     */
    private static final long serialVersionUID = 1L;
 
    private String id;
    private String title;
    private String[] content;
 
    public Message() {
        super();
    }
 
    public Message(String id, String title, String[] content) {
        super();
        this.id = id;
        this.title = title;
        this.content = content;
    }
 
    public String getId() {
        return id;
    }
 
    @Field("id")
    public void setId(String id) {
        this.id = id;
    }
 
    public String getTitle() {
        return title;
    }
 
    @Field("title")
    public void setTitle(String title) {
        this.title = title;
    }
 
    public String[] getContent() {
        return content;
    }
 
    @Field("content")
    public void setContent(String[] content) {
        this.content = content;
    }
 
}

 

Solr使用solr4J操作索引库的更多相关文章

  1. 使用solrj操作solr索引库

    (solrj)初次使用solr的开发人员总是很郁闷,不知道如何去操作solr索引库,以为只能用<五分钟solr4.5教程(搭建.运行)>中讲到的用xml文件的形式提交数据到索引库,其实没有 ...

  2. 使用solrj操作solr索引库,solr是lucene服务器

    客户端开发 Solrj 客户端开发 Solrj Solr是搭建好的lucene服务器 当然不可能完全满足一般的业务需求 可能 要针对各种的架构和业务调整 这里就需要用到Solrj了 Solrj是Sol ...

  3. JAVAEE——Solr:安装及配置、后台管理索引库、 使用SolrJ管理索引库、仿京东的电商搜索案例实现

    1 学习回顾 1. Lucene  是Apache开源的全文检索的工具包 创建索引 查询索引 2. 遇到问题? 文件名 及文件内容  顺序扫描法  全文检索 3. 什么是全文检索? 这种先创建索引 再 ...

  4. (转)淘淘商城系列——使用solrj来测试索引库

    http://blog.csdn.net/yerenyuan_pku/article/details/72892280 我们使用solrj来操作索引库,一般习惯先建一个单元测试类测试下增删改查方法是否 ...

  5. Lucene 07 - 对Lucene的索引库进行增删改查

    目录 1 添加索引 2 删除索引 2.1 根据Term删除索引 2.2 删除全部索引(慎用) 3 更新索引 数据保存在关系型数据库中, 需要实现增.删.改.查操作; 索引保存在索引库中, 也需要实现增 ...

  6. (转)淘淘商城系列——导入商品数据到索引库——Service层

    http://blog.csdn.net/yerenyuan_pku/article/details/72894187 通过上文的学习,我相信大家已经学会了如何使用Solrj来操作索引库.本文我们将把 ...

  7. 如何在分布式环境中同步solr索引库和缓存信息

    天气依旧很好,主要是凉快.老习惯,我在北京向各位问好. 搜索无处不在,相信各位每天都免不了与它的亲密接触,那么我想你确实有必要来了解一下它们,就上周在公司实现的一个小需求来给各位分享一下:如何在分布式 ...

  8. JAVAEE——宜立方商城07:Linux上搭建Solr服务、数据库导入索引库、搜索功能的实现

    1. 学习计划 1.Solr服务搭建 2.Solrj使用测试 3.把数据库中的数据导入索引库 4.搜索功能的实现 2. Solr服务搭建 2.1. Solr的环境 Solr是java开发. 需要安装j ...

  9. lucene&solr学习——solr学习(二) Solr管理索引库

    1.什么是solrJ solrj是访问Solr服务的java客户端,提供索引和搜索的请求方法,SolrJ通常在嵌入在业务系统中,通过SolrJ的API接口操作Solr服务,如下图: 依赖jar包: 2 ...

随机推荐

  1. method=“post/get”

    Form表单中method="post/get'的区别   Form提供了两种数据传输的方式——get和post.虽然它们都是数据的提交方式,但是在实际传输时确有很大的不同,并且可能会对数据 ...

  2. if....else

    if....else语句是在特定的条件下成立执行的代码,在不成立的时候执行else后面的代码. 语法: if(条件) {条件成立执行}else{条件不成立执行} 下面来写一个简单的实例 以考试成绩为例 ...

  3. inno setup 多语言安装

    之前的安装程序默认语言为英文,现在我们需要将它变成中文,由于InnoSetup安装包中默认没有带中文语言文件,我们需要下载一个先: 到http://www.400gb.com/u/758954/123 ...

  4. Oauth认证简介

    Oauth是什么: 1.Oauth是一种安全认证的协议: 2.Oauth为用户资源的授权提供了一个安全的.开放而又简易的标准: 3.Oauth的授权不会使第三方触及到用户的账号信息(用户名和密码). ...

  5. 未能解析目标框架“.NETFramework,Version=v4.0”的 mscorlib 错误的解决办法

    查看项目属性,发现该项目的目标框架是.NET Framework 4 Client Profile ,而被引用的程序集的目标框架是.NET Framework 4,将该项目的目标框架修改成.NET F ...

  6. C++最后课程项目总结

    第一次独立完成的C++小项目,40小时 + 5小时Update + 8小时Linux移植. 过程: 过程非常认真,一个星期主要就是忙这个,为了完成某个部分,有时饭都推迟吃,连续对着电脑10几个小时很累 ...

  7. 【C#枚举】根据EnumName获取Value

    public static int GetEnumValue(Type enumType, string enumName) { try { if (!enumType.IsEnum) throw n ...

  8. CSS3中动画transform必须要了解的Skew变化原理

    transform是CSS3中比较安全的动画(对于性能来说),其中有一些动画属性,来执行不同的变化.今天我们来了解skew的变化原理. skew,其实使用的频率不是很高,当然也没有最低.但是往往,一直 ...

  9. 不让input表单的输入框保存用户输入的历史记录

    如何不让input表单的输入框保存用户输入的历史记录.  有时我们在设计网页时不想让表单保存用户输入历史记录,比如一些隐私数据,或一些冲值卡 <input name="test&quo ...

  10. python中文字符串前加u

    我明明在编码前就加上了# -*- coding: UTF-8 -*-可是运行时还是出错了, # -*- coding: UTF-8 -*- 这句是告诉python程序中的文本是utf-8编码,让pyt ...