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
2.创建实体product
这里所有被添加Annotation @Field 注解的属性将参与index操作
package com.demo.solr.model; import org.apache.solr.client.solrj.beans.Field; public class Product { @Field private String id; @Field private String name; @Field private String keywords; @Field private String description; @Field private String sn; public Product() { super(); } public Product(String id, String name, String keywords, String description, String sn) { super(); this.id = id; this.name = name; this.keywords = keywords; this.description = description; this.sn = sn; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getSn() { return sn; } public void setSn(String sn) { this.sn = sn; } }