solrj简介
SolrJ基于httpClient:
使用SolrJ操作Solr会比利用httpClient来操作Solr要简单。
SolrJ是封装了httpClient方法,来操作solr的API的。
SolrJ底层还是通过使用httpClient中的方法来完成Solr的操作。
JAR包:
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>4.7.2</version>
</dependency>
Main方法中 ,调用SolrJ方法:(修改就是增加覆盖,增删改都要commit)
package org.last.solr;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrQuery.SortClause;
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.common.SolrDocument;
import org.apache.solr.common.SolrInputDocument;
import org.last.model.Student;
public class SolrJStu {
static String url = "http://127.0.0.1:8080/solr-web/core_stu";
static HttpSolrServer server = new HttpSolrServer(url); //实例化solrserver对象:指定索引库 my_core
public static void main(String[] args) throws Exception {
// List list = new ArrayList();
// Student stu = new Student();
// stu.setStuId(555);
// stu.setStuName("彭氏集团");
// stu.setStuAge(666);
// list.add(stu);
//
// add(list);
//
// 删除索引数据
// server.deleteByQuery("stuid:10011");
// server.commit();
//查询(检索)
SolrQuery query = new SolrQuery();//实例化一个查询query
query.setQuery("*");//查询用的参数(不写字段名,就会去找默认字段)
query.setStart(0);
query.setRows(25);
query.addSort(new SortClause("stuid", ORDER.desc));//根据id排序
QueryResponse response = server.query(query); //查询后返回 Response对象
List<SolrDocument> items = response.getResults();//获得Response对象中的结果集SolrDocument类型
for (SolrDocument i : items) {
//遍历 通过getFieldValue("字段名"),取值
System.out.println("ID: "+i.getFieldValue("stuid")+" 名称:"+i.getFieldValue("stuname"));
}
}
/**
* <pre>add(遍历增加索引数据)
* 创建人:彭榉 pengju918@sina.com
* 创建时间:2016年6月28日 上午10:55:45
* 修改人:彭榉 pengju918@sina.com
* 修改时间:2016年6月28日 上午10:55:45
* 修改备注: 统一提交,提高效率
* @param goods
* @throws SolrServerException
* @throws IOException</pre>
*/
public static void add(List<Student> stu) throws SolrServerException, IOException{
//创建 solr实体集合,最后将solr实体集合装入 solr索引库
List<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
//循环 将solr实体装入集合
for(Student s : stu){
SolrInputDocument doc = parese(s);
docs.add(doc); //遍历逐个增加
}
//将集合提交到 索引库
server.add(docs);
// commit后 使索引生效
server.commit();
}
/**
* <pre>parese(根据对应数据字段 进行数据添加 )
* 创建人:彭榉 pengju918@sina.com
* 创建时间:2016年6月28日 上午10:55:38
* 修改人:彭榉 pengju918@sina.com
* 修改时间:2016年6月28日 上午10:55:38
* 修改备注:
* @param good
* @return</pre>
*/
public static SolrInputDocument parese(Student stu){
//创建一个 solr实体 并以键值对的方式 添加数据到 该实体
SolrInputDocument sd = new SolrInputDocument();
sd.addField("stuid", stu.getStuId());
sd.addField("stuname", stu.getStuName());
sd.addField("studate", stu.getStuDate());
sd.addField("stuage", stu.getStuAge());
return sd;//返回一条个实体数据
}
}
=========================增加 实体bean==================================================================
实体类:
public class TestSolr {
public static void main(String[] args) throws IOException, SolrServerException {
String url = "http://localhost:8080/solr-test/my_core";
HttpSolrServer core = new HttpSolrServer(url); //实例化solrserver对象:指定索引库 my_core
// 删除全部数据
core.deleteByQuery("*:*");
// 增加两个对象
Item item = new Item();
item.setId(1);
item.setName("天下第一帅!");
item.setLast_update_time(new Date());
core.addBean(item);//添加对象到 核心(索引库)
Item item_cn = new Item();
item_cn.setId(2);
item_cn.setName("当然是彭榉");
item_cn.setLast_update_time(new Date());
core.addBean(item_cn);//添加对象到 核心(索引库)
//commit 以上的操作
core.commit();
//查询(检索)
SolrQuery query = new SolrQuery();//实例化一个查询query
query.setQuery("天下");//查询用的参数(不写字段名,就会去找默认字段)
query.addSort(new SortClause("id", ORDER.desc));//根据id排序
QueryResponse response = core.query(query); //查询后返回 Response对象
List<SolrDocument> items = response.getResults();//获得Response对象中的结果集SolrDocument类型
for (SolrDocument i : items) {
//遍历 通过getFieldValue("字段名"),取值
System.out.println("ID: "+i.getFieldValue("id")+" 名称:"+i.getFieldValue("name")+" 日期:"+i.getFieldValue("last_update_time"));
}
}
}
查询 分页
并且 设置关键词的 高亮:
public static void main(String[] args) {
//实例化solrserver对象
HttpSolrServer server = new HttpSolrServer("http://127.0.0.1:8088/solr-h/core_goods");
//创建要发送的SolrQuery对象 并设置参数(模糊,分页,排序等)
SolrQuery solrQuery = new SolrQuery();
solrQuery.set("q","gname:的");
solrQuery.set("sort", "gprice desc");
solrQuery.setStart(10);
solrQuery.setRows(25);
// 设置高亮
solrQuery.setHighlight(true);
solrQuery.setParam("hl.fl", "gname");
solrQuery.setHighlightSimplePre("<font color=\"red\">");
solrQuery.setHighlightSimplePost("</font>");
QueryResponse response;
try {
/* 这个客户端发起一个网络连接(通过HttpSolrServer中的query方法),发送查询条件,solr 执行查询,
然后返回结果到客户端,客户端将结果解析成 QueryResponse。
通过 QueryResponse 的 getResults() 方法得到查询到的文档,也可以通过其他方法从中得到高亮的结果。
*/
response = server.query(solrQuery);
SolrDocumentList list = response.getResults();
//第一个Map的键是文档的ID,第二个Map的键是高亮显示的字段名
Map<String, Map<String, List<String>>> map = response.getHighlighting();
for (SolrDocument g : list ) {
g.setField("gname", map.get(g.getFieldValue("gid")).get("gname"));
}
} catch (SolrServerException e) {
e.printStackTrace();
}
==================================拓展================================================
查询拼写检查(词汇联想、智能提醒)
package com.my.test3;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
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.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.SpellCheckResponse;
import org.apache.solr.client.solrj.response.SpellCheckResponse.Collation;
import org.apache.solr.client.solrj.response.SpellCheckResponse.Correction;
import org.apache.solr.client.solrj.response.SpellCheckResponse.Suggestion;
import com.my.entity.Item;
/**
* 查询拼写检查(词汇联想、智能提醒)
* @author admin
*
*/
public class TestSolr {
public static void main(String[] args) throws SolrServerException, IOException {
String url = "http://localhost:8080/solr/mycore1";
HttpSolrServer core = new HttpSolrServer(url);
core.setMaxRetries(1);
core.setConnectionTimeout(5000);
core.setParser(new XMLResponseParser()); // binary parser is used by default
core.setSoTimeout(1000); // socket read timeout
core.setDefaultMaxConnectionsPerHost(100);
core.setMaxTotalConnections(100);
core.setFollowRedirects(false); // defaults to false
core.setAllowCompression(true);
// ------------------------------------------------------
// remove all data
// ------------------------------------------------------
core.deleteByQuery("*:*");
// ------------------------------------------------------
// batch add
// ------------------------------------------------------
List<Item> items = new ArrayList<Item>();
items.add(makeItem(1, "cpu", "this is intel cpu", 1, "cpu-intel"));
items.add(makeItem(2, "cpu AMD", "this is AMD cpu", 2, "cpu-AMD"));
items.add(makeItem(3, "cpu intel", "this is intel-I7 cpu", 1, "cpu-intel"));
items.add(makeItem(4, "cpu AMD", "this is AMD 5000x cpu", 2, "cpu-AMD"));
items.add(makeItem(5, "cpu intel I6", "this is intel-I6 cpu", 1, "cpu-intel-I6"));
items.add(makeItem(6, "处理器", "中央处理器英特儿", 1, "cpu-intel"));
items.add(makeItem(7, "处理器AMD", "中央处理器AMD", 2, "cpu-AMD"));
items.add(makeItem(8, "中央处理器", "中央处理器Intel", 1, "cpu-intel"));
items.add(makeItem(9, "中央空调格力", "格力中央空调", 3, "air"));
items.add(makeItem(10, "中央空调海尔", "海尔中央空调", 3, "air"));
items.add(makeItem(11, "中央空调美的", "美的中央空调", 3, "air"));
core.addBeans(items);
// commit
// core.commit();
// ------------------------------------------------------
// search
// ------------------------------------------------------
SolrQuery query = new SolrQuery();
String token = "空调 中央";
query.set("qt", "/spellcheck");
query.set("q", token);
query.set("spellcheck", "on");
query.set("spellcheck.build", "true");
query.set("spellcheck.onlyMorePopular", "true");
// query.set("spellcheck.field", "content");
//提示查询的字符数量
query.set("spellcheck.count", "100");
query.set("spellcheck.alternativeTermCount", "4");
//点击率(更流行的)
query.set("spellcheck.onlyMorePopular", "true");
query.set("spellcheck.extendedResults", "true");
query.set("spellcheck.maxResultsForSuggest", "5");
//对应collate校验的结果
query.set("spellcheck.collate", "true");
query.set("spellcheck.collateExtendedResults", "true");
query.set("spellcheck.maxCollationTries", "5");
query.set("spellcheck.maxCollations", "3");
QueryResponse response = null;
try {
response = core.query(query);
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 {
core.shutdown();
}
SpellCheckResponse spellCheckResponse = response.getSpellCheckResponse();
if (spellCheckResponse != null) {
System.out.println("第一种获取方式》》》");
List<Suggestion> suggestionList = spellCheckResponse.getSuggestions();
for (Suggestion suggestion : suggestionList) {
System.out.println("Suggestions NumFound: " + suggestion.getNumFound());
System.out.println("Token: " + suggestion.getToken());
System.out.print("Suggested: ");
List<String> suggestedWordList = suggestion.getAlternatives();
for (String word : suggestedWordList) {
System.out.print(word + ", ");
}
System.out.println();
}
System.out.println();
System.out.println("第二种获取方式》》》");
Map<String, Suggestion> suggestedMap = spellCheckResponse.getSuggestionMap();
for (Map.Entry<String, Suggestion> entry : suggestedMap.entrySet()) {
System.out.println("suggestionName: " + entry.getKey());
Suggestion suggestion = entry.getValue();
System.out.println("NumFound: " + suggestion.getNumFound());
System.out.println("Token: " + suggestion.getToken());
//获取匹配结果集合
System.out.print("suggested: ");
List<String> suggestedList = suggestion.getAlternatives();
for (String suggestedWord : suggestedList) {
System.out.print(suggestedWord + ", ");
}
System.out.println("\n\n");
}
System.out.println("第三种获取方式》》》");
Suggestion suggestion = spellCheckResponse.getSuggestion(token);
if(null != suggestion){
//获取命中个数
System.out.println("NumFound: " + suggestion.getNumFound());
System.out.println("Token: " + suggestion.getToken());
System.out.print("suggested: ");
//获取匹配结果集合
List<String> suggestedList = suggestion.getAlternatives();
for (String suggestedWord : suggestedList) {
System.out.print(suggestedWord + ", ");
}
}
System.out.println("\n\n");
//返回的联想词中的第一个
System.out.println("The First suggested word for solr is : " + spellCheckResponse.getFirstSuggestion(token));
System.out.println("\n\n");
System.out.println("第四种获取方式:校验结果》》》");
//获取校验结果集
List<Collation> collatedList = spellCheckResponse.getCollatedResults();
if (collatedList != null) {
for (Collation collation : collatedList) {
//获取查询到的匹配字符串的值
System.out.println("collated query String: " + collation.getCollationQueryString());
//获取命中数量
System.out.println("collation Num: " + collation.getNumberOfHits());
//获取原始值和校验值的集合
List<Correction> correctionList = collation.getMisspellingsAndCorrections();
for (Correction correction : correctionList) {
//获取原始字符串的值
System.out.println("original: " + correction.getOriginal());
//获取纠正过后(校验过)的字符串的值
System.out.println("correction: " + correction.getCorrection());
}
System.out.println();
}
}
System.out.println();
//校验的最优结果
System.out.println("The Collated word: " + spellCheckResponse.getCollatedResult());
System.out.println();
}
System.out.println("查询耗时:" + response.getQTime());
}
private static Item makeItem(long id, String subject, String content, long categoryId, String categoryName) {
Item item = new Item();
item.setUsid(id);
item.setSubject(subject);
item.setContent(content);
item.setLast_update_time(new Date());
item.setCategoryId(categoryId);
item.setCategoryName(categoryName);
return item;
}
}
facet分片 主要功能是用于做统计、分类、区间等
package com.my.test2;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrQuery.SortClause;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.FacetField.Count;
import org.apache.solr.client.solrj.response.QueryResponse;
import com.my.entity.Item;
/**
* facet分片
* 主要功能是用于做统计、分类、区间等
* @author admin
*
*/
public class TestSolr {
public static void main(String[] args) throws SolrServerException, IOException {
String url = "http://localhost:8080/solr/mycore1";
HttpSolrServer core = new HttpSolrServer(url);
core.setMaxRetries(1);
core.setConnectionTimeout(5000);
core.setParser(new XMLResponseParser()); // binary parser is used by default
core.setSoTimeout(1000); // socket read timeout
core.setDefaultMaxConnectionsPerHost(100);
core.setMaxTotalConnections(100);
core.setFollowRedirects(false); // defaults to false
core.setAllowCompression(true);
// ------------------------------------------------------
// remove all data
// ------------------------------------------------------
core.deleteByQuery("*:*");
// ------------------------------------------------------
// batch add
// ------------------------------------------------------
List<Item> items = new ArrayList<Item>();
items.add(makeItem(1, "cpu", "this is intel cpu", 1, "cpu-intel"));
items.add(makeItem(2, "cpu AMD", "this is AMD cpusss", 2, "cpu-AMD"));
items.add(makeItem(3, "cpu intel", "this is intel-I7 cpu", 1, "cpu-intel"));
items.add(makeItem(4, "cpu AMD", "this is AMD 5000x cpusss", 2, "cpu-AMD"));
items.add(makeItem(5, "cpu intel I6", "this is intel-I6 cpu", 1, "cpu-intel-I6"));
core.addBeans(items);
// commit
// core.commit();
// ------------------------------------------------------
// search
// ------------------------------------------------------
SolrQuery query = new SolrQuery();
query.setQuery("*:*");
query.setStart(0); // query的开始行数(分页使用)
query.setRows(1); // query的返回行数(分页使用)
query.setFacet(true); // 设置使用facet
query.setFacetMinCount(1); // 设置facet最少的统计数量
query.setFacetLimit(10); // facet结果的返回行数
query.addFacetField("category_name", "content"); // facet的字段
query.setFacetPrefix("cpu"); // facet字段值
// query.setFacetPrefix("content", "cpu");
query.addSort(new SortClause("id", ORDER.asc)); // 排序
QueryResponse response = core.query(query);
List<Item> items_rep = response.getBeans(Item.class);
List<FacetField> facetFields = response.getFacetFields();
// 因为上面的start和rows均设置为0,所以这里不会有query结果输出
for (Item i : items_rep) {
System.out.println("id=" + i.getUsid() + "\tcontent=" + i.getContent());
}
System.out.println("****************************");
// 打印所有facet
for(FacetField ff : facetFields) {
// 分片字段名--------分片个数
System.out.println("name=" + ff.getName() + "\tcount=" + ff.getValueCount());
System.out.println("--------------------");
for(Count count: ff.getValues() ) {
//分片字段的值----出现次数
System.out.println("name=" + count.getName() + "\tvalue=" + count.getCount());
}
System.out.println("\n\n\n&&&&&&&&&&&&&&&&&&&&&&&");
}
}
private static Item makeItem(long id, String subject, String content, long categoryId, String categoryName) {
Item item = new Item();
item.setUsid(id);
item.setSubject(subject);
item.setContent(content);
item.setLast_update_time(new Date());
item.setCategoryId(categoryId);
item.setCategoryName(categoryName);
return item;
}
}
zookeeper客户端对节点的增删改查例子
package com.my.test4;
import java.io.IOException;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
/**
* zookeeper客户端对节点的增删改查例子
* @author admin
*
*/
public class TestZookeeper {
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
Watcher watcher = new Watcher() {
// 监控所有被触发的事件
public void process(WatchedEvent event) {
System.out.println("触发了" + event.getType() + "事件!");
}
};
// 第一个参数:ZooKeeper服务器的连接地址,如果ZooKeeper是集群模式或伪集群模式(即ZooKeeper服务器有多个),
// 那么每个连接地址之间使用英文逗号间隔,单个连接地址的语法格式为“主机IP:ZooKeeper服务器端口号”;
// 第二个参数:session超时时长(单位:毫秒)
// 第三个参数:用于监控目录节点数据变化和子目录状态变化的Watcher对象
ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, watcher);
// 创建一个节点名为“/RootNode”的目录节点
zooKeeper.create("/RootNode", "Root节点数据".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// 判断指定目录节点是否存在
System.out.println("“/RootNode”节点状态:" + zooKeeper.exists("/RootNode", true));
// 获取“RootNode”节点上的数据
System.out.println("“RootNode”节点上数据:" + new String(zooKeeper.getData("/RootNode", false, null)));
// 在“RootNode”节点下创建一个名为“ChildNode1”的子目录节点
zooKeeper.create("/RootNode/ChildNode1", "ChildNode1节点数据".getBytes(), Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
// 在“RootNode”节点下创建一个和“ChildNode1”同级的名为“ChildNode2”的子目录节点
zooKeeper.create("/RootNode/ChildNode2", "ChildNode2节点数据".getBytes(), Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
// 取出目录节点“RootNode”下的所有子目录节点
System.out.println("目录节点“RootNode”下的所有子目录节点有:" + zooKeeper.getChildren("/RootNode", true));
// 获取“RootNode/ChildNode2”节点上的数据
System.out.println("“ChildNode2”节点上数据:" + new String(zooKeeper.getData("/RootNode/ChildNode2", false, null)));
// 修改名为“ChildNode2”的目录节点数据
zooKeeper.setData("/RootNode/ChildNode2", "ChildNode2一道残阳铺水中".getBytes(), -1);
// 获取“RootNode/ChildNode2”节点上的数据
System.out.println("“ChildNode2”节点上数据:" + new String(zooKeeper.getData("/RootNode/ChildNode2", false, null)));
// 删除“/RootNode/ChildNode1”目录节点
zooKeeper.delete("/RootNode/ChildNode1", -1);
// 判断“/RootNode/ChildNode1”目录节点是否存在
System.out.println("“/RootNode/ChildNode1”节点状态:" + zooKeeper.exists("/RootNode/ChildNode1", false));
// 删除“/RootNode/ChildNode2”目录节点
zooKeeper.delete("/RootNode/ChildNode2", -1);
// 删除“/RootNode”目录节点
zooKeeper.delete("/RootNode", -1);
// 关闭与ZooKeeper的连接
zooKeeper.close();
}
}
欢迎各位大牛一起交流QQ:898190483,新人一个继续努力