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

简介: 首先有几点需要注意 客户端要调用solr服务,首先要把solr服务端工程启动,即前面文章讲的把solr下的slor.war例子放在tomcat下,进行相关配置,并启动。 (1)Exception in thread "main" org.apache.solr.client.solrj.beans.BindingException: class: class solr.PeopleBe

首先有几点需要注意

客户端要调用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/看看是否启动成功,

启动成功后的界面。


目录
相关文章
|
6月前
|
Java Linux 定位技术
Minecraft配置文件参数说明(JAVA服务器篇)
Minecraft JAVA版服务器启动后会生成server.properties配置文件,位于minecraft_server/根目录下。该文件包含多项关键设置,如游戏模式(gamemode)、最大玩家数(max-players)、难度(difficulty)等。此文档详细说明了各配置项的功能与默认值,帮助用户高效管理服务器环境。
1394 60
|
10月前
|
Java
java小工具util系列5:java文件相关操作工具,包括读取服务器路径下文件,删除文件及子文件,删除文件夹等方法
java小工具util系列5:java文件相关操作工具,包括读取服务器路径下文件,删除文件及子文件,删除文件夹等方法
202 9
|
6月前
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
|
11月前
|
运维 Java Linux
【运维基础知识】Linux服务器下手写启停Java程序脚本start.sh stop.sh及详细说明
### 启动Java程序脚本 `start.sh` 此脚本用于启动一个Java程序,设置JVM字符集为GBK,最大堆内存为3000M,并将程序的日志输出到`output.log`文件中,同时在后台运行。 ### 停止Java程序脚本 `stop.sh` 此脚本用于停止指定名称的服务(如`QuoteServer`),通过查找并终止该服务的Java进程,输出操作结果以确认是否成功。
567 1
|
16天前
|
弹性计算 编解码 大数据
性价比最高提升50%!阿里云企业级云服务器上新
阿里云ECS云服务器推出全新升级的u2系列实例,包括基于Intel的u2i实例与首个基于AMD的u2a实例,提供企业级独享算力,综合性价比最高提升50%。u2i实例已开放公测,适用于中小型数据库、企业网站建设等场景。同时发布基于AMD的第九代旗舰实例g9ae,性能提升65%,适用于大数据、视频转码等密集型业务。
106 1
|
27天前
|
弹性计算 运维 安全
阿里云轻量应用服务器是什么?看完你就知道了
阿里云轻量应用服务器是面向网站建设、开发测试等轻量场景的云服务器,按套餐售卖,内置多种应用镜像,支持一键部署,操作简单,适合个人开发者和中小企业使用。
194 0
|
2月前
|
存储 弹性计算 数据挖掘
阿里云2核4G5M带宽199元云服务器测评:价格、性能、适用场景与续费优势详解
阿里云目前活动中推出的“2核4G5M带宽199元1年”云服务器,是当下深受初创企业用户喜爱的云服务器。本文将从价格优势、性能优势和续费优势等几个方面,详细解析这款阿里云199元云服务器的各项特点,帮助大家更好地了解这款云服务器的性能和应用场景,以供选择参考。
|
30天前
|
存储 安全 数据挖掘
阿里云特惠云服务器轻量级38元,经济型99元,通用算力型199元性能、适用场景及选择参考
2025年,阿里云推出了3款特惠云服务器,轻量云服务器2核2G200M峰值带宽38元一年,经济型e实例云服务器2核2G3M带宽99元1年,通用算力型u1实例2核4G5M带宽199元1年。本文将深度解析这三款现象级产品的配置亮点、适用场景,以供参考和选择。
|
1月前
|
弹性计算 运维 负载均衡
阿里云轻量应用服务器产品介绍、收费标准以及搭建个人博客教程参考
本文为大家介绍阿里云轻量应用服务器的产品优势、应用场景、使用须知、地域与网络连通性、与云服务器ECS的区别以及使用轻量应用服务器搭建WordPress个人博客的图文教程,以供大家了解和使用轻量应用服务器。
|
2月前
|
存储
阿里云轻量应用服务器收费标准价格表:200Mbps带宽、CPU内存及存储配置详解
阿里云香港轻量应用服务器,200Mbps带宽,免备案,支持多IP及国际线路,月租25元起,年付享8.5折优惠,适用于网站、应用等多种场景。
513 0

热门文章

最新文章