solrj索引操作
添加索引
Solr添加文档至索引: http://www.cnblogs.com/dennisit/p/3621717.html
删除索引:
每天索引记录有一个唯一标识,索引的删除通过唯一标识操作,如下实例展示索引的删除.
删除单个索引
/**
* 根据id从索引中删除记录[测试通过]
* @param server
* @param idName 主键名
* @param id 主键值
*/
public static void deleteById(SolrServer server, String idName, Object id){
try {
server.deleteByQuery(idName + ":" + id.toString());
server.commit(false, false);
LOG.info("Delete from index by id" + id + " finished . operate param is:" + idName + ":" + id.toString());
} catch (Exception e) {
LOG.error("Delete from index by id" + id + " error, " + e.getMessage(), e);
}
}
批量删除索引
/**
* 根据id集合从索引中删除记录[测试通过]
* @param server
* @param ids
*/
public static <T> void deleteByIds(SolrServer server, String idName,List<T> ids){
try {
if (ids.size() > 0) {
StringBuffer query = new StringBuffer(idName + ":" + ids.get(0));
for (int i = 1; i < ids.size(); i++) {
if (null != ids.get(i)) {
query.append(" OR " + idName + ":" + ids.get(i).toString());
}
}
server.deleteByQuery(query.toString());
server.commit(false, false);
LOG.info("Delete from index by id list" + ids + " finished .");
}else{
LOG.info("Delete ids list is null.");
}
} catch (Exception e) {
LOG.error("Delete from index by id list" + ids + " error, " + e.getMessage(), e);
e.printStackTrace();
}
}
根据查询删除索引
/**
* 根据查询从索引中删除[测试通过]
* @param server
* @param queryString
*/
public static void deleteByQuery(SolrServer server,String query){
try {
server.deleteByQuery(query);
server.commit(false, false);
LOG.info("Delete from index by query string " + query + "finished .");
} catch (Exception e) {
LOG.error("Delete from index by query Strng " + query + "error, " + e.getMessage(), e);
e.printStackTrace();
}
}
根据对象删除
/**
* 根据对象删除,实质是根据Id删除
*
* @param server solr客户端
* @param object 删除的对象
* @param idName 对象的主键名
*/
public static void deleteBean(SolrServer server,Object object,String idName){
Class<?> cls = object.getClass();
try {
Method method = cls.getMethod(EntityConvert.dynamicMethodName(idName, "get"));
Object o = method.invoke(object);
if (o != null) {
deleteById(server,idName,method.invoke(object));
}
LOG.info("Delete from index by object" + object);
} catch (Exception e) {
LOG.error("Delete from index by object error, " + e.getMessage() ,e);
e.printStackTrace();
}
}
删除所有索引
/**
* 删除所有索引 [测试通过]
* @param server
*/
public static void deleteAllIndex(SolrServer server){
try {
server.deleteByQuery("*:*");
server.commit(false, false);
LOG.info("All index delete finished.");
} catch (Exception e) {
LOG.error("Delete all index error " + e.getMessage(), e);
e.printStackTrace();
}
}
修改索引
/**
* 更新单个记录 [测试通过]
* @author pudongping
*
* @param server
* Solr客户端
* @param object
* 要更新成的对象
* @param idName
* 主键id名
*/
public static void updateBean(SolrServer server,Object object,String idName){
if(null!=object && StringUtils.isNotBlank(idName)){
Class<?> clzz = object.getClass();
try {
Method method = clzz.getMethod(EntityConvert.dynamicMethodName(idName, "get"));
Object o = method.invoke(object);
if(null != o){
SolrQuery query = new SolrQuery();
query.setQuery(idName + ":" + o.toString());
query.setStart(0);
query.setRows(1);
QueryResponse response = server.query(query);
SolrDocument document = response.getResults().get(0);
LOG.info("更新一个记录" + EntityConvert.solrDocument2Entity(document, clzz));
System.out.println("更新一个记录" + EntityConvert.solrDocument2Entity(document, clzz));
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.setAction(AbstractUpdateRequest.ACTION.COMMIT, false, false);
updateRequest.add(solrDocument2SolrInputDocument(document, object));
updateRequest.process(server);
}
} catch (NoSuchMethodException e) {
LOG.error("Update bean error" + object);
e.printStackTrace();
} catch (IllegalAccessException e) {
LOG.error("Update bean error" + object);
e.printStackTrace();
} catch (IllegalArgumentException e) {
LOG.error("Update bean error" + object);
e.printStackTrace();
} catch (Exception e) {
LOG.error("Update bean error" + object);
e.printStackTrace();
}
}
}
所谓更新,无非是根据唯一标识查询出来,然后重新赋值.在solr中我们查询出来的结果为SolrDocument对象,而updateRequest.add(..)的对象为SolrInputDocument对象.所以我们需要编写这两个对象的转换
/**
* [测试通过]
*
* 更新数据时用到,给出要更新的对象,Id为必须给出的属性,然后加上要更新的属性
* 如果对应的属性的值为空或者为0,这不需要更新
*
* @param sd 查询到得SolrDocument
* @param object
* @return SolrInputDocument
*/
public static SolrInputDocument solrDocument2SolrInputDocument(SolrDocument sd, Object object) {
if (object != null && sd != null) {
SolrInputDocument sid = new SolrInputDocument();
Collection<String> fieldNameCollection = sd.getFieldNames(); // 得到所有的属性名
Class<?> cls = object.getClass();
Object o = null;
for (String fieldName : fieldNameCollection) {
try {
//需要说明的是返回的结果集中的FieldNames()比类属性多
Field[] filedArrays = cls.getDeclaredFields(); //获取类中所有属性
for (Field f : filedArrays) {
//如果实体属性名和查询返回集中的字段名一致,填充对应的set方法
if(f.getName().equals(fieldName)){ // 如果对应的属性的值为空或者为0,这不需要更新
o = cls.getMethod(EntityConvert.dynamicMethodName(fieldName, "get")).invoke(object);
Class<?> fieldType = cls.getDeclaredField(fieldName).getType(); if (fieldType.equals(Integer.TYPE)) {
Integer fieldValue = Integer.class.cast(o);
if (fieldValue != null && fieldValue.compareTo(0) != 0) {
sid.addField(fieldName, fieldValue);
}
} else if (fieldType.equals(Float.TYPE)) {
Float fieldValue = Float.class.cast(o);
if (fieldValue != null && fieldValue.compareTo(0f) != 0) {
sid.addField(fieldName, fieldValue);
}
} else if (fieldType.equals(Double.TYPE)) {
Double fieldValue = Double.class.cast(o);
if (fieldValue != null && fieldValue.compareTo(0d) != 0) {
sid.addField(fieldName, fieldValue);
}
} else if (fieldType.equals(Short.TYPE)) {
Short fieldValue = Short.class.cast(o);
if (fieldValue != null && fieldValue.compareTo((short)0) != 0) {
sid.addField(fieldName, fieldValue);
}
} else if (fieldType.equals(Long.TYPE)) {
Long fieldValue = Long.class.cast(o);
if (fieldValue != null && fieldValue.compareTo((long)0) != 0) {
sid.addField(fieldName, fieldValue);
}
} else if(fieldType.equals(List.class)){
List fieldValue = List.class.cast(o);
if(fieldValue != null){
sid.addField(fieldName, fieldValue);
}
}else {
if (o != null) {
sid.addField(fieldName, o.toString());
}
}
}
} } catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
LOG.error("请检查PO类中的field对应的各个setter和getter是否存在!");
e.printStackTrace();
} catch (NoSuchFieldException e) {
LOG.error("请检查schema中的field是否不存在于PO类中!");
e.printStackTrace();
}
}
return sid;
}
LOG.warn("即将要转换的SolrDocument或者要更新的Object为null");
return null;
}
查询索引
/**
* 根据关键字查询 [测试通过 - 使用 solr内部转换机制]
* @param <T>
* @param server solr客户端
* @param solrql sql查询串
* @param pageNum 当前页码
* @param pageSize 每页显示的大小
* @param clzz 对象类型
* @return
*/
public static <T>Page<T> query(SolrServer server,String solrql,int pageNum,int pageSize, Class<T> clzz){
SolrQuery query = new SolrQuery();
query.setQuery(solrql);
query.setStart((pageNum-1)*pageSize);
query.setRows(pageSize);
QueryResponse response = null;
try {
response = server.query(query);
} catch (SolrServerException e) {
e.printStackTrace();
return null;
} //查询到的记录总数
long totalRow = Long.valueOf(response.getResults().getNumFound()).intValue();
//查询结果集
List<T> items = response.getBeans(clzz);
//填充page对象
return new Page<T>(pageNum, pageSize, totalRow, items);
}
查询说明,参看这篇文章: http://www.cnblogs.com/huangfox/archive/2012/02/13/2348949.html
转载请注明出处:[http://www.cnblogs.com/dennisit/p/3623974.html]
solrj索引操作的更多相关文章
- Mongodb学习笔记三(Mongodb索引操作及性能测试)
第三章 索引操作及性能测试 索引在大数据下的重要性就不多说了 下面测试中用到了mongodb的一个客户端工具Robomongo,大家可以在网上选择下载.官网下载地址:http://www.robomo ...
- Elasticsearch-PHP 索引操作(转)
索引操作 本节通过客户端来介绍一下索引API的各种操作.索引操作包含任何管理索引本身(例如,创建索引,删除索引,更改映射等等). 我们通过一些常见的操作的代码片段来介绍,然后在表格中列出剩下的方法.R ...
- ElasticSearch+Kibana 索引操作
ElasticSearch+Kibana 索引操作 一 前言 ElasticiSearch 简介 ElasticSearch是一个基于Lucene的搜索服务器.它提供了一个分布式多用户能力的全文搜索引 ...
- Mysql之表的操作与索引操作
表的操作: 1.表的创建: create table if not exists table_name(字段定义); 例子: create table if not exists user(id in ...
- 3.Lucene3.x API分析,Director 索引操作目录,Document,分词器
1 Lucene卡发包结构分析 包名 功能 org.apache.lucene.analysis Analysis提供自带的各种Analyzer org.apache.lucene.colla ...
- Tensor索引操作
#Tensor索引操作 ''''' Tensor支持与numpy.ndarray类似的索引操作,语法上也类似 如无特殊说明,索引出来的结果与原tensor共享内存,即修改一个,另一个会跟着修改 ''' ...
- SQL Server死锁诊断--同一行数据在不同索引操作下引起的死锁
死锁概述 对于数据库中出现的死锁,通俗地解释就是:不同Session(会话)持有一部分资源,并且同时相互排他性地申请对方持有的资源,然后双方都得不到自己想要的资源,从而造成的一种僵持的现象.当然,在任 ...
- 获取列表的索引操作:enumerate
通过循环获取列表的索引操作: 主要使用:enumerate product_list = [['Iphone7',5800], ['Coffee',30], ['疙瘩汤',10], ['Python ...
- elasticsearch的索引操作和文档操作总结
参考文档:https://es.xiaoleilu.com/010_Intro/00_README.html 一.索引操作 1.查看当前节点的所有的index 查看当前节点的所有的index [roo ...
随机推荐
- colspan width issue
[问] I'm having trouble setting fixed widths on columns which use colspan. It seems that neither IE8, ...
- [PureScript] Introduce to PureScript Specify Function Arguments
JavaScript does its error-checking at runtime, but PureScript has a compiler, which makes sure that ...
- Masonry应用【美图秀秀首页界面自动布局】
Masonry在此实现时候,并没有比NSLayoutConstraint简单,相反我觉得还不如NSLayoutConstraint. [self.topView mas_makeConstraints ...
- Python爬虫实战(二):爬百度贴吧
代码: # _*_ coding:utf-8 _*_ import urllib import urllib2 import re class Tool: removingImg = re.compi ...
- PHPCMS源码分析
PHPCMS 一.模版引擎 如:调用单页面index.php?m=content&c=index&a=lists&catid=9.1.先获取到模版变量的值$template_l ...
- ArcGIS10.4 Runtime Error R6034
现在甲方采购的ArcGIS Desktop正版,一般都是较高的版本(10.4或10.4.1),但10.4经常报出C++ Runtime R6034错误. 问题 "Microsoft Visu ...
- 【转】web.xml不同版本的头
web.xml v2.3 <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web- ...
- 微信小程序 - 怎样合理设计小程序
假如我们无意中,把腾讯地图或者高德地图的管理Key删了! 关于定位的一切相关模块就都会报废! 接着呢?客户会找你,对你公司信任感下降,一系列问题接踵而来 最好的办法就是先预留key后台管理 “随时可以 ...
- 【Zookeeper】源码分析之请求处理链(三)之SyncRequestProcessor
一.前言 在分析了PrepRequestProcessor处理器后,接着来分析SyncRequestProcessor,该处理器将请求存入磁盘,其将请求批量的存入磁盘以提高效率,请求在写入磁盘之前是不 ...
- How do I fix a “Unknown configuration key `foreign-architecture' found in your `dpkg' configuration files.” error?
My /etc/dpkg/dpkg.cfg.d/multiarch contained: foreign-architecture i386 I deleted the file. I then is ...