Solr 6安装与solr-solrj客户端基本使用

本文环境为centos6,且已安装好jdk8,下载solr-6.3.0.zip,并解压,目录为/software/solr-6.3.0

1、启动solr,使用命令./solr start -force完成启动,如下

[root@localhost2 bin]# cd /software/solr-6.3.0/bin/

[root@localhost2 bin]# ./solr start -force

Archiving 1 old GC log files to /software/solr-6.3.0/server/logs/archived
Archiving 1 console log files to /software/solr-6.3.0/server/logs/archived
Rotating solr logs, keeping a max of 9 generations
NOTE: Please install lsof as this script needs it to determine if Solr is listening on port 8983.

Started Solr server on port 8983 (pid=2284). Happy searching!

[root@localhost2 bin]#

启动成功后即可使用浏览器访问 http://192.168.1.220:8983/solr 查看到solr管理控制台 关闭可使用命令 ./solr stop -all

2、创建一个core,命令如下

[root@localhost2 bin]# ./solr create -c bill -force


Copying configuration to new core instance directory:
/software/solr-6.3.0/server/solr/bill

Creating new core 'bill' using command:
http://localhost:8983/solr/admin/cores?action=CREATE&name=bill&instanceDir=bill

{
  "responseHeader":{
    "status":0,
    "QTime":952},
  "core":"bill"}


[root@localhost2 bin]# 

同样可使用命令./solr delete -c bill 删除一个core

3、进入管理控制台首页,点击core select选择刚刚创建的core bill如图所示 solr 再选择Schema,如下所示 solr 接着增加几个字段用以测试(本文摘取游戏充值片断完成基本测试)

id 唯一标识(默认索引值标识,此字段无需添加)
dealDate 充值日期
amount 充值金额
type 充值类型
createDate 创建日期
remark 备注

依次添加dealDate amount type createDate remark字段,注意字段类型分别为string double int date string solr 创建完成后可点左边栏 Query 打开查询页面,点击Execute Query 执行查询,即可完成查询,目前还没有数据,

4、使用solr-solrj客户端完成索引的建立,删除,查找等功能。 编写pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.hode</groupId>
	<artifactId>solr</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
        <spring.version>4.3.2.RELEASE</spring.version>
        <junit.version>4.12</junit.version>
        <log4j.version>1.2.17</log4j.version>
        <mongodb.version>1.9.0.RELEASE</mongodb.version>
        <slf4j.version>1.7.12</slf4j.version>
    </properties>
    
	<dependencies>

		<dependency>
			<groupId>org.apache.solr</groupId>
			<artifactId>solr-solrj</artifactId>
			<version>6.1.0</version>
		</dependency>

		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.1</version>
		</dependency>
		
		<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
		
		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
        
        <dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.8.0</version>
		</dependency>
		
		<dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>
        
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>

		</plugins>
	</build>

</project>

编写一个model类Recharge.java

package com.hode.model;

import java.util.Date;

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

public class Recharge {

	@Field
    private String id;
    
    @Field
    private String dealDate;
    
    @Field
    private double amount;
    
    @Field
    private int type;
    
    @Field
    private String remark;

    @Field
    private Date createDate;
    
	public Recharge() {
		super();
	}

	public Recharge(String id, String dealDate, double amount, int type, String remark,Date createDate) {
		super();
		this.id = id;
		this.dealDate = dealDate;
		this.amount = amount;
		this.type = type;
		this.remark = remark;
		this.createDate = createDate;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getDealDate() {
		return dealDate;
	}

	public void setDealDate(String dealDate) {
		this.dealDate = dealDate;
	}

	public double getAmount() {
		return amount;
	}

	public void setAmount(double amount) {
		this.amount = amount;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}
    
}

再编写一个测试类如下

package com.hode;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.FieldStatsInfo;
import org.apache.solr.client.solrj.response.Group;
import org.apache.solr.client.solrj.response.GroupCommand;
import org.apache.solr.client.solrj.response.GroupResponse;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.MapSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.junit.Before;
import org.junit.Test;

import com.google.gson.Gson;
import com.hode.model.Recharge;

public class RechargeTest {

private static final String URL = "http://192.168.1.220:8983/solr/bill";
	
	private static HttpSolrClient solrClient = null;
	
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
	
	private Gson gson = new Gson();
	
	private String[][] TYPE = { {"1","支付宝"},{"2","微信"},{"3","财付通"} };
	
	@Before
	public void init(){
        solrClient = new HttpSolrClient.Builder(URL).build();
        solrClient.setConnectionTimeout(3000);
    }
	
	// 清除数据
	@Test
	public void clearData() {
		try {
			UpdateResponse resp = solrClient.deleteByQuery("*:*");
			System.out.println(gson.toJson(resp));
			resp = solrClient.commit();
			System.out.println(gson.toJson(resp));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//添加索引数据
	@Test
	public void addData(){
		String id = sdf.format(new Date());
		String dealDate = "2015010"+new Random().nextInt(10);
		double amount = new BigDecimal(new Random().nextDouble()*1000).setScale(2, RoundingMode.HALF_UP).doubleValue();
		int type = new Random().nextInt(3);
		String remark = String.format("%s充值%s元",TYPE[type][1],amount);
		
		Recharge r = new Recharge(id, dealDate, amount, type+1, remark ,new Date());
		
		try{
		    UpdateResponse resp = solrClient.addBean(r);
		    System.out.println(gson.toJson(resp));
			solrClient.commit();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	//按条件搜索数据
	@Test
	public void testSearchData(){
	    Map<String, String> map = new HashMap<String, String>();
        map.put("q", "(type:1 OR type:2) AND amount:[100 TO *]");
        map.put("start", "0");
        map.put("rows", "5");
        map.put("sort", "createDate asc");
        SolrParams params = new MapSolrParams(map);
        System.out.println(params.toQueryString());
	    try{
	        QueryResponse response = solrClient.query(params);
	        
	        List<Recharge> list = response.getBeans(Recharge.class);
	        for(Recharge t:list){
	            System.out.println(gson.toJson(t));
	        }
        }catch(Exception e){
            e.printStackTrace();
        }
	}
	
	//统计充值金额
	@Test
	public void testStatsData(){
	    Map<String, String> map = new HashMap<String, String>();
	    map.put("q", "(type:1 OR type:2) AND amount:[100 TO *]");
        map.put("stats", "true");
        map.put("stats.field", "amount");
        SolrParams params = new MapSolrParams(map);
        System.out.println(params.toQueryString());
	    try{
	        QueryResponse response = solrClient.query(params);
	        /*SolrDocumentList list = response.getResults();
	        for(SolrDocument sd : list){
	            System.out.println(gson.toJson(sd));
	        }*/
	        
	        Map<String, FieldStatsInfo> result = response.getFieldStatsInfo();
	        FieldStatsInfo info = result.get("amount");
	        System.out.println(info);
	        System.out.println(info.getSum());
        }catch(Exception e){
            e.printStackTrace();
        }
	}
	
	//分组统计笔数
	@Test
	public void testGroupData(){
	    Map<String, String> map = new HashMap<String, String>();
	    map.put("q", "(type:1 OR type:2 OR type:3) AND amount:[1 TO *]");
        map.put("group", "true");
        map.put("group.field", "type");
        SolrParams params = new MapSolrParams(map);
        System.out.println(params.toQueryString());
	    try{
	        QueryResponse response = solrClient.query(params);

	        
	        GroupResponse result = response.getGroupResponse();
	        List<GroupCommand> l = result.getValues();
	        for(GroupCommand gc:l){
	        	List<Group> v = gc.getValues();
	        	for(Group g:v){
	        		//System.out.println(gson.toJson(g));
	        		System.out.println(TYPE[Integer.valueOf(g.getGroupValue())-1][1]+" "+g.getResult().getNumFound()+" 笔");
	        	}
	        }
        }catch(Exception e){
            e.printStackTrace();
        }
	}

}

可先运行方法 addData() ,添加一些基础数据,再使用其他测试方法查询结果,同样在solr管理控制台也可以查询到结果。

结束。


赞赏(Donation)
微信(Wechat Pay)

donation-wechatpay