一 创建java程序,引入jar包
依赖的jar
二 入门程序
2.1 新增/更新索引
public class SolrDemo { HttpSolrServer httpSolrServer = null; @Before public void init() { //连接索引库 String baseUrl = "http://localhost/solr/article"; httpSolrServer = new HttpSolrServer(baseUrl); } //保存或更新 id不存在即保存,id存在即更新 @Test public void UpdateOrSave() throws Exception { //创建文档对象 SolrInputDocument doc = new SolrInputDocument(); doc.addField("id","1"); doc.addField("title","我是程序员"); doc.addField("content","我爱敲代码"); //提交 httpSolrServer.add(doc); httpSolrServer.commit(); } }
2.2 查询
1普通查询
//查询 查询条件格式 "*:*" 即"指定的字段:指定检索的内容" @Test public void QueryDemo() throws Exception { SolrQuery solrQuery = new SolrQuery("title:程序"); QueryResponse queryResponse = httpSolrServer.query(solrQuery); SolrDocumentList results = queryResponse.getResults(); for (SolrDocument result : results) { System.out.println(result.get("id")); System.out.println(result.get("title")); System.out.println( result.get("content")); System.out.println(result.get("keywords")); } }
2 高亮查询 ,对查询的内容进行修饰
//高亮查询 @Test public void HighLightQueryDemo() throws Exception { //设置查询条件 SolrQuery solrQuery = new SolrQuery("title:程序"); //设置高亮字段 solrQuery.addHighlightField("title"); //开启高亮 solrQuery.setHighlight(true); //设置开始标签 solrQuery.setHighlightSimplePre("<font color='red'>"); //设置结束标签 solrQuery.setHighlightSimplePost("</font>"); QueryResponse queryResponse = httpSolrServer.query(solrQuery); //普通结果 SolrDocumentList results = queryResponse.getResults(); //高亮结果 Map<String, Map<String, List<String>>> highlight = queryResponse.getHighlighting(); for (SolrDocument result : results) { String id = result.get("id").toString(); System.out.println("id= " + id); System.out.println("普通title"+result.get("title")); System.out.println("高亮title"+highlight.get(id).get("title")); System.out.println( result.get("content")); System.out.println(result.get("keywords")); System.out.println(highlight); } }
打印结果:
id= 1 普通title我是程序员 高亮title[我是<font color='red'>程序</font>员] 我爱敲代码 [我是程序员, 我爱敲代码] {1={title=[我是<font color='red'>程序</font>员]}}
2.3删除
执行前可多插入几条数据
1.根据id删除
//删除 根据id删除 @Test public void deleteById() throws IOException, SolrServerException { httpSolrServer.deleteById("3"); httpSolrServer.commit(); }
2.根据条件删除
@Test public void deleteByQuery() throws IOException, SolrServerException { //先查询后删除 httpSolrServer.deleteByQuery("title:程序"); httpSolrServer.commit(); }
3.删除所有
//删除所有 @Test public void deleteAll() throws IOException, SolrServerException { httpSolrServer.deleteByQuery("*:*"); httpSolrServer.commit(); }
ok