使用solrj查询数据(java代码)

时间:2022-06-24 10:58:24

实体类Student,添加Field注解

package com.cs.solr.entity;

import org.apache.solr.client.solrj.beans.Field;

public class Student {
@Field("id")
private Integer id;
@Field("name")
private String name;
@Field("gender")
private String gender;
@Field("major")
private String major;
@Field("grade")
private String grade; public Student() {
super();
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getGender() {
return gender;
} public void setGender(String gender) {
this.gender = gender;
} public String getMajor() {
return major;
} public void setMajor(String major) {
this.major = major;
} public String getGrade() {
return grade;
} public void setGrade(String grade) {
this.grade = grade;
}
}

查询的java代码。

package com.cs.teset;

import java.util.List;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList; import com.cs.solr.entity.Student; public class SolrQueryTest {
private static int connectionTimeout = 60000;
private static int soTimeout = 60000;
private static int maxRetries = 1;
private static int defaultMaxCOnnectionPerhost = 100;
private static int maxTotalConnections = 100;
private static boolean followRedirects = false;
private static boolean allowCompression = true;
public static void main(String[] args) throws ClassNotFoundException {
queryAll();
} public static void queryAll() throws ClassNotFoundException {
try {
HttpSolrServer server = new HttpSolrServer(
"http://localhost:8983/solr/mycore");
server.setSoTimeout(soTimeout);
server.setConnectionTimeout(connectionTimeout);
server.setDefaultMaxConnectionsPerHost(defaultMaxCOnnectionPerhost);
server.setMaxTotalConnections(maxTotalConnections);
server.setFollowRedirects(followRedirects);
server.setAllowCompression(allowCompression);
server.setMaxRetries(maxRetries);
SolrQuery params = new SolrQuery("*:*");// 查询所有
QueryResponse qs = server.query(params);
SolrDocumentList results = qs.getResults();
List<Student> list =qs.getBeans(Student.class);
for (Student student : list) {
System.out.println(student.getName());
}
//System.out.println(list);
} catch (SolrServerException e) {
e.printStackTrace();
}
}
}