隐藏

Java 对 solr 的增删改查,java源码

发布:2024/1/27 17:51:00作者:管理员 来源:本站 浏览次数:757

solr 安装配置完成后,如何在java代码中应用起来呢。

首先我们先创建一个类 solrUtils.java

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
[java]
//                         _ooOoo_  
//                        o8888888o  
//                        88" . "88  
//                        (| -_- |)  
//                         O\ = /O  
//                     ____/`---'\____  
//                   .   ' \\| |// `.  
//                    / \\||| : |||// \  
//                  / _||||| -:- |||||- \  
//                    | | \\\ - /// | |  
//                  | \_| ''\---/'' | |  
//                   \ .-\__ `-` ___/-. /  
//                ___`. .' /--.--\ `. . __  
//             ."" '< `.___\_<|>_/___.' >'"".  
//            | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//              \ \ `-. \_ __\ /__ _/ .-` / /  
//      ======`-.____`-.___\_____/___.-`____.-'======  
//                         `=---='  
//
//      .............................................  
//               佛祖保佑             永无BUG 
//       佛曰:  
//               写字楼里写字间,写字间里程序员;  
//               程序人员写程序,又拿程序换酒钱。  
//               酒醒只在网上坐,酒醉还来网下眠;  
//               酒醉酒醒日复日,网上网下年复年。  
//               但愿老死电脑间,不愿鞠躬老板前;  
//               奔驰宝马贵者趣,公交自行程序员。  
//               别人笑我忒疯癫,我笑自己命太贱;  
//               不见满街漂亮妹,哪个归得程序员? 
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
 
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrInputDocument;
 
import com.jfinal.kit.PropKit;
import com.sunjs.kit.ToolsUtils;
import com.sunjs.model.TBlogArticle;
 
public class SolrUtils {
     
    protected static final Logger LOG = Logger.getLogger(SolrUtils.class);
 
    private final static String BASE_URL = "http://localhost:8983/solr/sunjs";
 
    /**
     * 创建SolrServer对象
     
     * 该对象有两个可以使用,都是线程安全的 1、CommonsHttpSolrServer:启动web服务器使用的,通过http请求的 2、
     * EmbeddedSolrServer:内嵌式的,导入solr的jar包就可以使用了 3、solr
     * 4.0之后好像添加了不少东西,其中CommonsHttpSolrServer这个类改名为HttpSolrClient
     
     * @return
     */
    public static SolrClient createSolrServer() {
        return new HttpSolrClient.Builder(BASE_URL).build();
    }
 
    public static Integer addDucument(TBlogArticle article) {
        if(article==null){
            return 30850;
        }
        Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
 
        SolrInputDocument doc = new SolrInputDocument();
        doc.addField("id", article.getLong("id"));
        doc.addField("category_id", article.getLong("category_id"));
        doc.addField("uuid", article.getStr("uuid"));
        doc.addField("visit_num", article.getInt("visit_num"));
        doc.addField("pic_url", article.getStr("pic_url"));
        doc.addField("author", article.getStr("author"));
        doc.addField("tags", article.getStr("tags"));
        doc.addField("tags_name", article.getStr("tags_name"));
        doc.addField("title", article.getStr("title"));
        doc.addField("digest", article.getStr("digest"));
        doc.addField("add_time", article.getDate("add_time"));
        docs.add(doc);
        SolrClient solrClient = createSolrServer();
        try {
            solrClient.add(docs);
            UpdateResponse rspcommit = solrClient.commit();
            return rspcommit.getStatus()==0?30800:30850;
        catch (Exception e) {
            e.printStackTrace();
            LOG.info(ToolsUtils.print("solr","索引失败", article.getStr("title"), e.getMessage()));
        finally{
            try {
                LOG.info(ToolsUtils.print("solr","索引成功", article.getStr("title")));
                solrClient.close();
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        return 30850;
    }
     
    public static Integer deleteById(Object id) {
        if(id!=null && StringUtils.isEmpty(id+"")){
            return 30892;
        }
        SolrClient solrClient = createSolrServer();
        try {
            if(id.equals("*")){
                //删除所有
                // Preparing the Solr document
                solrClient.deleteByQuery("*");
                UpdateResponse rspcommit = solrClient.commit();
                return rspcommit.getStatus()==0?30891:30892;
            }else{
                solrClient.deleteById(id+"");
                UpdateResponse rspcommit = solrClient.commit();
                return rspcommit.getStatus()==0?30891:30892;
            }
        catch (SolrServerException | IOException e) {
            e.printStackTrace();
            LOG.info(ToolsUtils.print("solr","删除索引失败""ID:"+id, e.getMessage()));
        finally{
            try {
                LOG.info(ToolsUtils.print("solr","删除索引成功""ID:"+id));
                solrClient.close();
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        return 30892;
    }
 
}
public static Page<TBlogArticle> queryFromSolr(Integer pageNumber, Integer pageSize, String reqparam) {
        Page<TBlogArticle> page = new Page<TBlogArticle>();
        if(StringUtils.isEmpty(reqparam)){
            reqparam="*";
        }
 
        SolrQuery query = new SolrQuery();
        query.setHighlight(true);
        query.addHighlightField("digest");
        query.addHighlightField("title");
        query.setHighlightSimplePre("<font color=\"red\">");
        query.setHighlightSimplePost("</font>");
//        query.setHighlightSnippets(1);
//        query.setHighlightFragsize(2);
        query.setStart((pageNumber-1)*pageSize);
        query.setRows(pageSize);
        query.set("q""title:"+reqparam+" OR "+"digest:"+reqparam);
        List<TBlogArticle> articles = new ArrayList<TBlogArticle>();
        SolrClient solrClient = createSolrServer();
        try {
            QueryResponse response = solrClient.query(query);
            SolrDocumentList docList = response.getResults();
            Map<String, Map<String, List<String>>> highlightMap = response.getHighlighting();
             
            Iterator<SolrDocument> it = docList.iterator();
            while (it.hasNext()) {
                SolrDocument doc = it.next();
                Long id = Long.valueOf(doc.getFieldValue("id").toString());
                Long category_id = Long.valueOf(doc.getFieldValue("category_id")==null?"0":doc.getFieldValue("category_id").toString());
                Integer visit_num = Integer.valueOf(doc.getFieldValue("visit_num")==null?"0":doc.getFieldValue("visit_num").toString());
                String uuid = doc.getFieldValue("uuid")==null?null:doc.getFieldValue("uuid").toString();
                String pic_url = doc.getFieldValue("pic_url")==null?null:doc.getFieldValue("pic_url").toString();
                String author = doc.getFieldValue("author")==null?null:doc.getFieldValue("author").toString();
                String tags = doc.getFieldValue("tags")==null?null:doc.getFieldValue("tags").toString();
                String tags_name = doc.getFieldValue("tags_name")==null?null:doc.getFieldValue("tags_name").toString();
                String title = doc.getFieldValue("title")==null?null:doc.getFieldValue("title").toString();
                String digest = doc.getFieldValue("digest")==null?null:doc.getFieldValue("digest").toString();
                Date add_time = (Date)doc.getFieldValue("add_time");
                 
                TBlogArticle article = new TBlogArticle();
                article.set("id", id);
                article.set("category_id", category_id);
                article.set("uuid", uuid);
                article.set("visit_num", visit_num);
                article.set("pic_url", pic_url);
                article.set("author", author);
                article.set("tags", tags);
                article.put("tags_name", tags_name);
                article.set("title", title);
                article.set("digest", digest);
                article.put("title_html", title);
                article.put("digest_html", digest);
                article.set("add_time", add_time);
                 
                List<String> titleList=highlightMap.get(id+"").get("title");
                List<String> digestList=highlightMap.get(id+"").get("digest");
                //获取并设置高亮的字段title
                if(titleList!=null && titleList.size()>0){
                    article.put("title_html", titleList.get(0));
                }
                //获取并设置高亮的字段content
                if(digestList!=null && digestList.size()>0){
                    article.put("digest_html", digestList.get(0));
                }
                articles.add(article);
            }
            Integer totalRow = Integer.valueOf(docList.getNumFound()+"");
            Integer totalPage = (int) (totalRow % pageSize == 0 ? totalRow / pageSize : Math.ceil((double)totalRow / (double)pageSize)) ;
            page = new Page<TBlogArticle>(articles, pageNumber, pageSize, totalPage, totalRow);
        catch (SolrServerException e) {
            e.printStackTrace();
        catch (IOException e) {
            e.printStackTrace();
        finally{
            try {
                solrClient.close();
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        return page;
    }

上边可能有部分类报异常,不过都无关紧要,主要代码都在。

如果查询出来的字段:doc.getFieldValue 是一个数组,也就是多列。那么只需要在配置文件中操作一下即可:

进入 /Users/sun/Documents/solr-6.5.1/server/solr/my_core/conf 这个目录下,打开managed-schema

找到是数组的列,比如是add_time:

1
[xml]
<field name="add_time" type="tdates" multiValued="false"/>

增加 multiValued="false" 即可!


如何想要删除全部索引

1
[java]
SolrUtils.deleteById("*");

删除执行id 为 1 的索引

1
[java]
SolrUtils.deleteById(1);