1. Import related Jar packages
<dependency> <groupId>org.apache.solr</groupId> <artifactId>solr-solrj</artifactId> <version>6.5.0</version> </dependency> <!-- Test code is used, no need to add --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.12</version> </dependency>
2. Call Solr to search data
* Solr test class SolrTest.java
public class SolrTest { private static Logger log = LogManager.getLogger(); public static void main(String[] args) throws Exception { String solrUrl = "http://localhost:10001/solr/core_test"; HttpSolrClient client = new HttpSolrClient.Builder(solrUrl).build(); SolrQuery query = new SolrQuery(); query.set("wt", "json"); // Query string, the query name has James/Curry, and the age is 20 to 30 (inclusive) records query.set("q", "name:(James Curry) AND age:[20 TO 30]"); // Which fields are included in the returned record, multiple separated by commas and spaces query.set("fl", "id,name,age"); query.set("sort", "age ASC,name DESC"); // Filter query: age range 25~30 // query.set("fq", "age:[25 TO 30]"); // ***********Highlight setting start*********** // enable highlighting query.set("hl", "true"); // highlight field query.set("hl.fl", "name"); // Highlight format (front) query.set("hl.simple.pre", "<span>"); // Highlight format (after) query.set("hl.simple.post", "</span>"); // ***********Highlight setting end*********** // Paging, the returned data starts from the first record query.setStart(0); // Paginate, return the number of records query.setRows(10); // QueryResponse response = client.query(query); SolrDocumentList result = response.getResults(); // List<Star> starList = response.getBeans(Star.class); log.info("total:{},start:{},end:{}",result.getNumFound(),result.getStart(),result.getStart()+result.size()); log.info("----------List data----------"); for (Star star : starList) { log.info(JSONObject.toJSONString(star)); } log.info("----------Highlight----------"); Map<String, Map<String, List<String>>> hlMap = response.getHighlighting(); Iterator<Entry<String, Map<String, List<String>>>> hlIterator = hlMap.entrySet().iterator(); while(hlIterator.hasNext()){ Entry<String, Map<String, List<String>>> hlItem = hlIterator.next(); log.info("id->{},highlight->{}",hlItem.getKey(),hlItem.getValue()); } } }
* Solr search record corresponds to entity class Star.java
import org.apache.solr.client.solrj.beans.Field; public class Star { @Field("id") private String id; @Field("name") private String name; @Field("age") private int age; 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 int getAge() { return age; } public void setAge(int age) { this.age = age; } }search results:
2017-04-21 17:17:37.765 [main] INFO - total:2,start:0,end:2 cn.tinyf.demo.solr.SolrTest 2017-04-21 17:17:37.766 [main] INFO - ---------- list data ---------- cn.tinyf.demo.solr.SolrTest 2017-04-21 17:17:37.820 [main] INFO - {"age":27,"id":"66654e81-c1a9-4961-b782-5513f0928f2a","name":"James Harden"} cn.tinyf.demo.solr.SolrTest 2017-04-21 17:17:37.820 [main] INFO - {"age":28,"id":"18f483cc-afda-4cc5-926e-5035bc427239","name":"Curry"} cn.tinyf.demo.solr.SolrTest 2017-04-21 17:17:37.820 [main] INFO - ----------Highlight---------- cn.tinyf.demo.solr.SolrTest 2017-04-21 17:17:37.820 [main] INFO - id->66654e81-c1a9-4961-b782-5513f0928f2a,highlight->{name=[<span>James</span> Harden]} cn.tinyf.demo.solr.SolrTest 2017-04-21 17:17:37.821 [main] INFO - id->18f483cc-afda-4cc5-926e-5035bc427239,highlight->{name=[<span>Curry</span>]} cn.tinyf.demo.solr.SolrTest3. Add & update documents (records) The main methods for updating are (the back brackets indicate that there are overloaded methods with this parameter):
- addBean(Object [,int])
- add(SolrInputDocument [,int])
import org.apache.solr.client.solrj.impl.HttpSolrClient; import cn.tinyf.demo.Utils; public class SolrUpdateTest { private static Scanner reader; public static void main(String[] args) throws Exception { String solrUrl = "http://localhost:10001/solr/core_test"; HttpSolrClient solrClient = null; try { // construct input reader = new Scanner(System.in); // create a new solr client solrClient = new HttpSolrClient.Builder(solrUrl).build(); int menu = 0; String line = null; Star data; while ((menu = selectMenu()) != 0) { switch (menu) { // add documentation case 1: System.out.println(">>>Add record<<<"); System.out.print("Please enter name: "); line = reader.nextLine(); if (Utils.isEmpty(line)) { break; } data = new Star(); data.setName(line); System.out.print("Please enter age: "); line = reader.nextLine(); if (Utils.isEmpty(line) || !line.trim().matches("\\d*")) { break; } data.setAge(Integer.parseInt(line)); data.setId(Utils.uuid()); solrClient.addBean (date, 100); System.out.println(">>>To do add next,id->" + line); break; // Revise case 2: System.out.println(">>>Modify record<<<"); System.out.print("Please enter the record ID: "); line = reader.nextLine(); if (Utils.isNotEmpty(line)) { solrClient.deleteById(line); } data = new Star(); data.setId(line); System.out.print("Please enter name: "); line = reader.nextLine(); if (Utils.isEmpty(line)) { break; } data.setName(line); System.out.print("Please enter age: "); line = reader.nextLine(); if (Utils.isEmpty(line) || !line.trim().matches("\\d*")) { break; } data.setAge(Integer.parseInt(line)); solrClient.addBean (date, 100); System.out.println(">>>To do update next,id->" + line); break; // delete case 3: System.out.println(">>>delete record<<<"); System.out.print("Please enter the record ID: "); line = reader.nextLine(); if (Utils.isNotEmpty(line)) { solrClient.deleteById(line); } System.out.println(">>>To do delete next,id->" + line); break; // commit the changes immediately case 4: System.out.println(">>>Commit right now!"); solrClient.commit(); break; default: break; } } } catch (Exception e) { e.printStackTrace (); } finally { reader.close(); if (solrClient != null) { solrClient.commit(); } } } private static int selectMenu() { do { System.out.println("******Solr Menu******"); System.out.println("*1.Add record"); System.out.println("*2.Update record"); System.out.println("*3. Delete record"); System.out.println("*4. Commit changes"); System.out.println("*0.退出"); System.out.print("********************\nPlease select: "); String line = reader.nextLine(); if (line.matches("\\s*[0-4]\\s*")) { return Integer.parseInt(line); } else { System.out.println(">>>Select wrong(" + line + "), please reselect <<<"); } } while (true); } }Back to Contents