您的位置:首页 > 其它

solrj demo 索引创建与查询

2015-06-07 22:03 405 查看
solrj作为solr的java客户端使得solr的开发简单了许多,solrJ实际上也是是封装了httpClient方法,来操作solr的API的。

下面来通过一个简单的demo实现solrj的索引创建以及查询

demo需求:需要对一个product 的实体创建以及查询索引(字段包括id,name,keywords,description,sn)

一,首先根据需要在solr配置文件schema.xml中配置相应的field(这边我只需要增加sn字段即可,其他都直接使用了默认存在的field)

<!-- for csop product
<field name="id"        type="string" indexed="true" stored="true" />
<field name="name"        type="string" indexed="true" stored="true" />
<field name="keywords"        type="string" indexed="true" stored="true" />
<field name="description"      type="string" indexed="true" stored="true" />  -->
<field name="sn"        type="string" indexed="true" stored="true" />
<!-- for csop product over -->


二,创建测试项目

1.所需jar包

除了solrj的jar还需要一下jar

package com.demo.solr;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.solr.client.solrj.SolrServerException;

import com.demo.solr.model.Product;

public class Startup {

public static void main(String[] args) throws IOException, ParseException, SolrServerException {
System.out.println(new Date());
testSearch();
System.out.println(new Date());
}

public static void testInsert() throws IOException, SolrServerException{
List<Product> products =new ArrayList<Product>();
Random ran = new Random();
File dataFile=new File("E://data.txt");
FileWriter fileWriter=new FileWriter(dataFile);
BufferedWriter bw=new BufferedWriter(fileWriter);
for(int i=0;i<100;i++){
String id=UUID.randomUUID().toString();
String name="test"+i+ran.nextInt(5000);
String sn="sn-"+333;
String keywords="just test-"+UUID.randomUUID().toString().replace("-", "");
products.add(new Product(id, name, keywords, null, sn));
bw.write(id);
bw.write("\t");

bw.write(name);
bw.write("\t");
bw.write(keywords);
bw.write("\t");
bw.write(sn);
bw.newLine();
}
fileWriter.flush();
bw.close();
fileWriter.close();
System.out.println(products.size());

SolrIndexUtils.addIndexs(products);
}

public static void testSearch() throws SolrServerException, IOException{
List<Product> search = SolrQueryUtils.search("test2833", null, null, null, 0, 20);
for (Product product : search) {

System.out.println(product.getId()+"||||||"+product.getName());
}
}
}


Startup

你也可以通过这里查看wiki上的实例,不过貌似是老版本了通过SolrServer创建客户端的方式在新版本中已经不推荐,而使用改为SolrClient了

https://wiki.apache.org/solr/Solrj
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: