首先,在可以根据ip:端口能够进入solr服务器的基础上,solr所有配置都配好的基础上。。。。。。。。。。。。。。。
1、导包,在这里我用的是7.0.1的包,在晚上看到的都是四点几包,绕了很大一圈,很多方法都不一样了,只有一个包
org.apache.solr
solr-solrj
7.0.1
2、配置一个spring-solr.xml
3、在这里我是将solr交给spring管理的,只写了service层跟serviceImpl
@Service
public class SolrImpl implements IsolrService {
@Autowired
HttpSolrClient client;
@Override
public List solr(String text) throws IOException, SolrServerException {
SolrQuery query=new SolrQuery();
String queryText="infoName:"+text+"* or infoArtist:"+text+" or infoAddress:"+text+"*";
query.set("q",queryText);
//1、过滤器
//query.set("fq","infoPrice:[1 TO 1000]");
//2、排序
//query.set("sort","infoPrice desc","id asc");
//3、设置查询到的文档返回的域对象
query.set("fi","id,infoName,infoArtist,infoAddress");
//4、设置默认查询的域
query.set("df","infoName","infoArtist","infoAddress");
//5.分页
query.set("start",0);
query.set("rows",10);
//6、高亮
//设置高亮域(设置的域必须在查询条件中存在)
query.addHighlightField("infoName");
query.addHighlightField("infoArtist");
query.addHighlightField("infoAddress");
//前缀
query.setHighlightSimplePre("");//这里的话,如果用thymeleaf模板,css样式生效需要加th:utext...
//后缀
query.setHighlightSimplePost("");
QueryResponse response = client.query(query);
//普通查询
SolrDocumentList results = response.getResults();
List comList=new ArrayList();
//高亮查询
NamedList namedList= (NamedList) response.getResponse().get("highlighting");
//k是id,内部的map的key是域名,其value是高亮的值集合
/*Map>> highlighting = response.getHighlighting();*/
System.out.println("匹配的结果总数是-------"+results.getNumFound());
for(SolrDocument document:results){
CommodityInfoDto comInfo=new CommodityInfoDto();
Integer id=Integer.parseInt((String)document.get("id"));
comInfo.setInfoId(id);;
comInfo.setInfoName((String)document.get("infoName"));
comInfo.setInfoImg((String)document.get("infoImg"));
comInfo.setInfoArtist((String)document.get("infoArtist"));
comInfo.setInfoTime((String)document.get("infoTime"));
comInfo.setInfoAddress((String)document.get("infoAddress"));
comInfo.setInfoPrice((String)document.get("infoPrice"));
comInfo.setInfoTicket((String)document.get("infoTicket"));
for(int i=0;i0){
String highInfoName=(String)infoName.get(0);
comInfo.setInfoName(highInfoName);
}
ArrayList infoArtist = (ArrayList) map.get("infoArtist");
if(infoArtist!=null&& infoArtist.size()>0){
String highinfoArtist=(String)infoArtist.get(0);
comInfo.setInfoArtist(highinfoArtist);
}
ArrayList infoAddress = (ArrayList) map.get("infoAddress");
if(infoAddress!=null&& infoAddress.size()>0){
String highinfoAddress=(String)infoAddress.get(0);
comInfo.setInfoArtist(highinfoAddress);
}
}
}
comList.add(comInfo);
}
return comList;
}
}
4、我这里是通过用户输入一个字符,里面内容包括商品名字+商品艺人姓名+商品地址,联合查询,查询出来的对象也不会是重复的数据
//查询商品
@Test
public void test11(){
try {
List list = solr.solr("演唱");
for(CommodityInfoDto com:list){
System.out.println("-------------->"+com);
}
} catch (IOException e) {
e.printStackTrace();
} catch (SolrServerException e) {
e.printStackTrace();
}
}
}
5、结果看看