在上一篇文章中已经学了SolrJ的增删改。本篇来学习下查询的一些实例
(还未了解SolrJ 增删改的可以查看以上博文:http://blog.csdn.net/weijonathan/article/details/16963437)
1、查询排序
public static void solrOrder() throws SolrServerException { solrCore = new HttpSolrServer(url); SolrQuery query = new SolrQuery(); query.setQuery("*:*"); query.addSortField("id", SolrQuery.ORDER.asc); QueryResponse rsp = solrCore.query(query); List<App> beans = rsp.getBeans(App.class); for (int i = 0; i < beans.size(); i++) { System.out.println(beans.get(i).getName()); } }使用addSortField可将查询出来的结果按照你指定的字段进行排序
2、模糊查询
public static void likeQuery() throws SolrServerException { solrCore = new HttpSolrServer(url); SolrQuery query = new SolrQuery(); query.setQuery("name:*天天*"); QueryResponse rsp = solrCore.query(query); List<App> beans = rsp.getBeans(App.class); for (int i = 0; i < beans.size(); i++) { System.out.println(beans.get(i).getName()); } }模糊查询其实很简单,因为solr本身就支持正则查询,所以通过setQuery指定你要查询的字段,以及要做模糊查询的值就搞定了!
3、分页查询
public static void pageQuery() throws SolrServerException { solrCore = new HttpSolrServer(url); SolrQuery query = new SolrQuery(); query.setQuery("name:*天天*"); query.setStart(0); query.setRows(10); QueryResponse rsp = solrCore.query(query); List<App> beans = rsp.getBeans(App.class); for (int i = 0; i < beans.size(); i++) { System.out.println(beans.get(i).getName()); } }这里用到了setStart以及setRows方法进行分页
4、多条件 ||(或)的情况
public static void multipleQuery1() throws SolrServerException { solrCore = new HttpSolrServer(url); SolrQuery query = new SolrQuery(); query.setQuery("artist:*Tencent* name:*天天*");// 多条件使用空格分隔 query.setFields("name", "id_in_appstore", "artist"); QueryResponse rsp = solrCore.query(query); List<App> beans = rsp.getBeans(App.class); for (int i = 0; i < beans.size(); i++) { System.out.println(beans.get(i).getName()); System.out.println(beans.get(i).getArtist()); System.out.println(beans.get(i).getId_in_appstore()); } }在setQuery中设置多个查询条件,多个查询条件中间用空格隔开就ok
5、多条件& (且)的情况:
public static void multipleQuery2() throws SolrServerException { solrCore = new HttpSolrServer(url); SolrQuery query = new SolrQuery(); query.setQuery("name:*天天*");// 多条件使用空格分隔 query.setFilterQueries("artist:*Tencent*"); query.setFields("name", "id_in_appstore", "artist"); QueryResponse rsp = solrCore.query(query); List<App> beans = rsp.getBeans(App.class); for (int i = 0; i < beans.size(); i++) { System.out.println(beans.get(i).getName()); System.out.println(beans.get(i).getArtist()); System.out.println(beans.get(i).getId_in_appstore()); } }name包含"天天"且artist包含“Tencent”
对于普通的查询,以上这些查询已经足够了!但是对于复杂的查询当然光靠这些是远远不够的。
后面会有博文介绍更加复杂的查询。