版权声明:本站所提供的文章资讯、软件资源、素材源码等内容均为本作者提供、网友推荐、互联网整理而来(部分报媒/平媒内容转载自网络合作媒体),仅供学习参考,如有侵犯您的版权,请联系我,本作者将在三个工作日内改正。 https://blog.csdn.net/weixin_42323802/article/details/84503084
solr进行范围超找时候抛异常:
1、问题描述:
solrJ中进行范围搜索时候报错:
org.apache.solr.client.solrj.beans.BindingException: Could not instantiate object of class com.baidu.Item
Caused by: org.apache.solr.client.solrj.beans.BindingException: Exception while setting value
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.String field com.baidu.Item.title to java.util.ArrayList
2、解决办法
- solr\core1\conf\schema.xml 文件中设置filed 为title字段的multiValued=“true”
- 更改Javabean 的title 为ArrayList 类型;
》这里采用第二种方式,更改Javabean
》在路径 :G:\tools\solr\core1\conf\schema.xml找到配置文件
可以看到 field 属性配置如下:
可以看到 filed 为title字段的multiValued=“true” ;
所以需要更改 multiValued=“true” 为multiValued=“false”
2.1、Javabean 以及测试 testQueryToJavabean如下:
- Item 类
- testQueryToJavabean单元测试
public class Item implements Serializable {
private static final long serialVersionUID=1L;
@Field("id")
private String id;
@Field("title")
private ArrayList title;
@Field("price")
private long price;
// 提供 setter 、getter方法 重写toString
}
在这里插入代码片
@Test
public void testQueryToJavabean() throws IOException, SolrServerException {
HttpSolrServer server = new HttpSolrServer("http://localhost:8080/solr/core1");
/**
* 普通查询
*/
// SolrQuery query = new SolrQuery("title:iphone");
/**
* boolean 查询
*/
// SolrQuery query = new SolrQuery("title:iphone OR title:小米");
/**
* 相似度查询 ,类似于Lucene的编辑距离0-2
*/
// SolrQuery query = new SolrQuery("title:ipHOne~2");
/**
* 范围查询 xx TO xx
* 闭区间
*/
SolrQuery query = new SolrQuery("price:[10 TO 10000]");
//
QueryResponse response = server.query(query);
List<Item> itemList = response.getBeans(Item.class);
for (Item item : itemList) {
System.out.println(item);
}
System.out.println("搜多到的条数:" + itemList.size());
}
2.1再测,
尼玛,有提示float 类型非法,打开schema.xml 中查找price 的相关配置:
》发现price 配置是float ,行吧,更改Javabean以及插入core1索引库的price属性为float
1、javabean更改
public class Item implements Serializable {
private static final long serialVersionUID=1L;
@Field("id")
private String id;
@Field("title")
private String title;
@Field("price")
private Float price;
// 提供 setter 、getter方法 重写toString
}
2、更新core1索引库中price的属性为float 类型
/**
* pojo中属性没有注解@Field,导致solrJ并不知道哪个属性要对应到索引库中
* @throws IOException
* @throws SolrServerException
*/
@Test
public void testCreateIndexBean() throws IOException, SolrServerException {
HttpSolrServer server = new HttpSolrServer("http://localhost:8080/solr/core1");
//
Item item = new Item();
item.setId("9");
item.setPrice(3000F);
item.setTitle("小米手机");
// server中添加bean
server.addBean(item);
server.commit();
}
3、单元测试走一走,完美解决:
ok