java 调用solr服务器 实现增删改查 及高亮显示

版权声明:GOOD DEEP https://blog.csdn.net/u013378306/article/details/50761771

首先有几点需要注意

客户端要调用solr服务,首先要把solr服务端工程启动,即前面文章讲的把solr下的slor.war例子放在tomcat下,进行相关配置,并启动。

(1)Exception in thread "main" org.apache.solr.client.solrj.beans.BindingException: class: class solr.PeopleBean does not define any fields.
是因为使用实体bean添加索引时,没有在实体属性上添加 Filed注解,导致solr无法匹配

@Field("name")
public void setName(String name) {
this.name = name;
}

public String[] getContent() {
return content;
}

(2)org.apache.solr.client.solrj.impl.HttpSolrServer$RemoteSolrException: Expected mime type application
是因为当solr有多个core时,solrj操作时没有指定是哪个core,以下指定使用core0的数据

private final static String URL = "http://localhost:80/solr/core0";
HttpSolrServer server = new HttpSolrServer(URL);

(3)Exception in thread "main" org.apache.solr.client.solrj.beans.BindingException: Could not instantiate object of class solr.PeopleBean

是因为当QueryResponse.getBeans(PeopleBean.class);方式查询,并返回实体bean时,必须有一个空的构造方法

public PeopleBean(){//此处应该注意,当QueryResponse.getBeans(PeopleBean.class);方式查询,并返回实体bean时,必须有一个                           空的构造方法

}

(4)当明明有数据却查不到时,要注意查询的字段,是否开启了索引。即 在shema.xml中是否设置indexed="true"

<field name="id"        type="string"   indexed="true"  stored="true"  multiValued="false" required="true"/>

<field name="name"      type="text_ik"   indexed="true"  stored="false"  multiValued="false" /> 

 <field name="content"      type="text_ik"   indexed="false"  stored="true"  multiValued="true" /> 

其中 indexed="true" 表示开启索引(当字段不需要被检索时,最好不要开启索引,) stored="true"表示存储原来数据(当字段不被检索,而只是需要通过其他字段检索而获得时,要设为true)  multiValued="true" 表示返回多值,如一个返回多个content,此时要在java代码中把 content设置 集合或数组类型如 

private String[] content;//多值,对应 multiValued="true"

(5)

需要以下jar包


上面的一些jar可以从下载的solr压缩包中获得


其他的就是一些日志依赖jar如,commons-logging-1.1.1.jar,slf4j-log4j12-1.5.8.jar,log4j-1.2.14.jar

下面附上代码(注意运行代码时先把solr服务端工程启动,路径为http://localhost:80/solr/core0

工程大概


schema.xml文件

<?xml version="1.0" ?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<schema name="example core zero" version="1.5">
	<fieldType name="text_ik" class="solr.TextField">
		<analyzer type="index" isMaxWordLength="false" class="org.wltea.analyzer.lucene.IKAnalyzer"/>
		<analyzer type="query" isMaxWordLength="false" class="org.wltea.analyzer.lucene.IKAnalyzer"/>
	</fieldType>
   <fieldtype name="string"  class="solr.StrField" sortMissingLast="true" omitNorms="true"/>
   <fieldType name="long" class="solr.TrieLongField" precisionStep="0" positionIncrementGap="0"/>
  <!-- general -->
  <field name="id"        type="string"   indexed="true"  stored="true"  multiValued="false" required="true"/>

  <field name="name"      type="text_ik"   indexed="true"  stored="true"  multiValued="false" /> 
   <field name="content"      type="text_ik"   indexed="true"  stored="true"  multiValued="true" /> 
  <field name="_version_" type="long"     indexed="true"  stored="true"/>

 <!-- field to use to determine and enforce document uniqueness. -->
 <uniqueKey>id</uniqueKey>

 <!-- field for the QueryParser to use when an explicit fieldname is absent -->
 <defaultSearchField>name</defaultSearchField>

 <!-- SolrQueryParser configuration: defaultOperator="AND|OR" -->
 <solrQueryParser defaultOperator="OR"/>
</schema>

实体PeopleBean


package solr;

import java.util.List;

import org.apache.solr.client.solrj.beans.Field;

public class PeopleBean {

	private String id;
	private String name;
	private String[] content;//多值,对应 multiValued="true"
	
	
	
	public String getId() {
		return id;
	}
	@Field
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	@Field("name")
	public void setName(String name) {
		this.name = name;
	}
	
	public String[] getContent() {
		return content;
	}
	@Field
	public void setContent(String[] content) {
		this.content = content;
	}
	public PeopleBean(){//此处应该注意,当QueryResponse.getBeans(PeopleBean.class);方式查询,并返回实体bean时,必须有一个空的构造方法
		
	}
	public PeopleBean(String id, String name, String[] content) {
		this.id = id;
		this.name = name;
		this.content = content;
	}
	


	
	
}

增加 索引 SolrAdd

package solr;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Test;

public class SolrAdd {

	private final static String URL = "http://localhost:80/solr/core0";
	public static void  add(){
		
		//1、创建SolrServer对象,该对象有两个可以使用,都是线程安全的
//		HttpSolrServer:启动web服务器使用的,通过http请求的
//		EmbeddedSolrServer:内嵌式的,导入solr的jar包就可以使用了
		try {
			HttpSolrServer server = new HttpSolrServer(URL);
			//把查询出来的数据全部删除
//			server.deleteByQuery("*:*");
//			server.commit();
			
			SolrInputDocument doc = new SolrInputDocument();
			//id是必填的,并且是String类型的
			//<field name="id" type="string" indexed="true" stored="true" required="true" />
			//id是唯一的主键,当多次添加的时候,最后添加的相同id会覆盖前面的域
			doc.addField("id", "5");
			doc.addField("name", "这是我的第一个solrj程序");
			doc.addField("content", "solr程序的运行");
			server.add(doc);
			server.commit();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 基于列表的添加
	 * @throws SolrServerException
	 * @throws IOException
	 */
	public static void test2() throws SolrServerException, IOException{
		List<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
		SolrInputDocument doc = new SolrInputDocument();
		doc.addField("id", "7");
		doc.addField("name", "很好,solr可以工作了");
		doc.addField("content", "solr总算可以正式工作了");
		
		docs.add(doc);
		
		doc = new SolrInputDocument();
		doc.addField("id", "8");
		doc.addField("name", "测试以下solr的添加");
		doc.addField("content", "看看能不能添加一个列表信息");
		
		docs.add(doc);
		
		HttpSolrServer server = new HttpSolrServer(URL);
		server.add(docs);
		server.commit();
	}
	
	/**
	 * 基于javabean的添加
	 * @throws SolrServerException
	 * @throws IOException
	 */
	public static void test3() throws SolrServerException, IOException{
		List<PeopleBean> msgs = new ArrayList<PeopleBean>();
		//多值域的添加使用数组
		msgs.add(new PeopleBean("9","基于javabean的添加9",new String[]{"这是content9","这是dddddddddcontent9"} ));
		msgs.add(new PeopleBean("10","基于javabean的列表数据的添加10", new String[]{"solr这是content10","这是conteooooooooont10"}));
		
		HttpSolrServer server = new HttpSolrServer(URL);
		server.addBeans(msgs);
		server.commit();
	}
	public static void main(String[] args) throws Exception {
		test3();
	}
}

根据索引查询 SolrSelect,及高亮显示字符串(高亮显示实际上是给指定的字符串添加css样式)

package solr;

import java.net.MalformedURLException;
import java.util.List;

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.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;

public class SolrSelect {
	private final static String URL = "http://localhost:80/solr/core0";//注意当多core时,要指定一个core,不然会报错
	HttpSolrServer server = new HttpSolrServer(URL);
	
	/**
	 * 返回filed
	 * @throws SolrServerException
	 * @throws MalformedURLException
	 */
	public static void select() throws SolrServerException, MalformedURLException{
		HttpSolrServer server = new HttpSolrServer(URL);
		//定义查询字符串
		SolrQuery query = new SolrQuery("基于javabean的添加9");
		String s[]=query.getFilterQueries();
		//实现分页的查询
		query.setStart(0);
		query.setRows(3);
		QueryResponse res = server.query(query);
		//查询出来的结果都保存在SolrDocumentList中
		SolrDocumentList sdl = res.getResults();
		System.out.println("总数:"+sdl.getNumFound());
		for(SolrDocument sd : sdl){
			System.out.println(sd.get("id")+"#"+sd.get("name")+"#"+sd.get("content"));
		}
	}
	
	/**
	 * 返回bean
	 * @throws MalformedURLException
	 * @throws SolrServerException
	 */
	public static void select2() throws MalformedURLException, SolrServerException{
		HttpSolrServer server = new HttpSolrServer(URL);
		//相当于QueryParser
		SolrQuery query = new SolrQuery("*:*");
		query.setStart(1);
		query.setRows(3);
		QueryResponse res = server.query(query);
		//可以直接查询相应的bean对象,但是不是很常用
		//使用这种方式无法获取总数量
		List<PeopleBean> list = res.getBeans(PeopleBean.class);
		System.out.println("当前总数:"+list.size());
		for(PeopleBean msg : list){
			System.out.println(msg.getId()+"#"+msg.getName()+"#"+msg.getContent());
		}
	}
	
	/**
	 * 高亮显示
	 * @throws SolrServerException
	 * @throws MalformedURLException
	 */
	 public static void color() throws SolrServerException, MalformedURLException{  
		 HttpSolrServer server = new HttpSolrServer(URL);
	        SolrQuery query = new SolrQuery("name:基于"); //高亮字符:基于
	        query.setHighlight(true).setHighlightSimplePre("<span class='red'>").setHighlightSimplePost("</span>")  
	        .setStart(0).setRows(10);  
	        //hl.fl表示高亮的field,也就是高亮的区域  
	        query.setParam("hl.fl","name","content");  //显示高亮的字段
	        QueryResponse res = server.query(query);  
	          
	        SolrDocumentList sdl = res.getResults();  
	        System.out.println("总数:"+sdl.getNumFound());  
	        for(SolrDocument sd : sdl){  
//	          System.out.println(sd.get("id")+"#"+sd.get("msg_title")+"#"+sd.get("msg_content"));  
	            String id = (String) sd.get("id");  
	            //在solr这里对需要加高亮的字段必须要在索引中的store=true才行  
	            System.out.println(id+"#"+res.getHighlighting().get(id).get("name"));;  
	              
	        }  
	    }  
	public static void main(String[] args) throws Exception {
		select2();
	}

}

删除 SolrDelete

package solr;

import org.apache.solr.client.solrj.impl.HttpSolrServer;

public class SolrDelete {
	private final static String URL = "http://localhost:80/solr/core0";
	 static HttpSolrServer solrServer = new HttpSolrServer(URL);
	 /**
	  * 根据id删除
	  * @param id
	  */
	 public static void deleteById(String id) {
	        try {
	        	
	            solrServer.deleteById(id+"");
	            solrServer.commit();
	        } catch (Exception e) {
	        	 System.out.println("错误");
	        }
	    }
	    
	    /**
	     * 删除所有文档,为安全起见,使用时再解注函数体 。
	     */
	    public static void deleteAll() {
	        try {
	            solrServer.deleteByQuery("*:*");
	            solrServer.commit();
	        } catch (Exception e) {
	            System.out.println("错误");
	        }
	    }
	public static void main(String[] args) {
		//deleteById("1");
		deleteAll();
	}
}

修改 SolrUpdate (修改实际上还是增加索引,只不过指定id,把相同id的filed覆盖掉)


package solr;

import java.io.IOException;
import java.net.MalformedURLException;

import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.SolrInputDocument;

public class SolrUpdate {
	private final static String URL = "http://localhost:80/solr/core0";
public static void  update(){
		try {
			HttpSolrServer server = new HttpSolrServer(URL);
			SolrInputDocument doc = new SolrInputDocument();
			doc.addField("id", "5");
			doc.addField("name", "这是我的第一个solrj程序");
			doc.addField("content", "solr程序的运行");
			server.add(doc);
			server.commit();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		update();//更新其实是覆盖id=**的filed
		
	}

}


注意先启动solr服务端,服务端启动后先http://localhost:80/solr/看看是否启动成功,

启动成功后的界面。


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页