需要的jar包
代码
public class SolrTest {
@After
public void tearDown() throws Exception {
}
@Test
public void testAdd() throws SolrServerException, IOException {
String url=
"http://localhost:8080/solr";
SolrServer solrServer=
new HttpSolrServer(url);
SolrInputDocument document =
new SolrInputDocument();
document.addField(
"id",
"solr001");
document.addField(
"product_name",
"魅族手机");
document.addField(
"product_price",
3000);
solrServer.add(document);
solrServer.commit();
}
@Test
public void deleteDocumentById() throws Exception{
String url=
"http://localhost:8080/solr";
SolrServer solrServer=
new HttpSolrServer(url);
solrServer.deleteById(
"solr001");
solrServer.commit();
}
@Test
public void deleteAll()throws Exception{
String url=
"http://localhost:8080/solr";
SolrServer solrServer=
new HttpSolrServer(url);
solrServer.deleteByQuery(
"*:*");
solrServer.commit();
}
@Test
public void testSearch() throws Exception{
String url=
"http://localhost:8080/solr";
SolrServer solrServer=
new HttpSolrServer(url);
SolrQuery solrQuery =
new SolrQuery();
solrQuery.
set(
"df",
"product_name");
solrQuery.setQuery(
"手机");
solrQuery.addFilterQuery(
"product_price:[100 TO 6600]");
solrQuery.setSort(
"product_price", ORDER.asc);
solrQuery.setStart(
0);
solrQuery.setRows(
10);
solrQuery.setFields(
"id",
"product_name",
"product_price");
solrQuery.setHighlight(
true);
solrQuery.addHighlightField(
"product_name");
solrQuery.setHighlightSimplePre(
"<span style='color:red'>");
solrQuery.setHighlightSimplePost(
"</span>");
QueryResponse queryResponse = solrServer.query(solrQuery);
SolrDocumentList results = queryResponse.getResults();
System.
out.println(
"查询结果总量:"+results.getNumFound());
for (SolrDocument solrDocument : results) {
System.
out.println(solrDocument.
get(
"id"));
System.
out.println(solrDocument.
get(
"product_name"));
System.
out.println(solrDocument.
get(
"product_price"));
System.
out.println(solrDocument.
get(
"product_catalog_name"));
System.
out.println(solrDocument.
get(
"product_picture"));
Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
Map<String, List<String>> map = highlighting.
get(solrDocument.
get(
"id"));
List<String> list = map.
get(
"product_name");
System.
out.println(list.
get(
0));
System.
out.println(
"--------------");
}
}
}