`
mxsfengg
  • 浏览: 206255 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

solr1.3新特性,solrj的使用

    博客分类:
  • solr
阅读更多

CommonsHttpSolrServer

    CommonsHttpSolrServer 使用HTTPClient 和solr服务器进行通信。

String url = "http://localhost:8983/solr";
  SolrServer server = new CommonsHttpSolrServer( url );

 

   CommonsHttpSolrServer 是线程安全的,建议重复使用CommonsHttpSolrServer 实例。

  Setting XMLResponseParser

     sorlr J 目前使用二进制的格式作为默认的格式。对于solr1.2的用户通过显示的设置才能使用XML格式。

   

server.setParser(new XMLResponseParser());

 

   Changing other Connection Settings

      CommonsHttpSorlrServer 允许设置链接属性。

     

String url = "http://localhost:8983/solr"
  CommonsHttpSolrServer server = new CommonsHttpSolrServer( url );
  server.setSoTimeout(1000);  // socket read timeout
  server.setConnectionTimeout(100);
  server.setDefaultMaxConnectionsPerHost(100);
  server.setMaxTotalConnections(100);
  server.setFollowRedirects(false);  // defaults to false
  // allowCompression defaults to false.
  // Server side must support gzip or deflate for this to have any effect.
  server.setAllowCompression(true);
  server.setMaxRetries(1); // defaults to 0.  > 1 not recommended.

 

EmbeddedSolrServer

      EmbeddedSorrServer提供和CommonsHttpSorlrServer相同的接口,它不需要http连接。

     

//注意,下面的属性也是可以在jvm参数里面设置的
  System.setProperty("solr.solr.home", "/home/shalinsmangar/work/oss/branch-1.3/example/solr");
  CoreContainer.Initializer initializer = new CoreContainer.Initializer();
  CoreContainer coreContainer = initializer.initialize();
  EmbeddedSolrServer server = new EmbeddedSolrServer(coreContainer, "");  

  

   如果你想要使用 Multicore 特性,那么你可以这样使用:

  

 File home = new File( getSolrHome() );
    File f = new File( home, "solr.xml" );
    multicore.load( getSolrHome(), f );

    EmbeddedSolrServer server = new EmbeddedSolrServer( multicore, "core name as defined in solr.xml" );

 

    如果你在你的项目中内嵌solr服务,这将是一个不错的选择。无论你能否使用http,它都提供相同的接口。

  用法

    solrj 被设计成一个可扩展的框架,用以向solr服务器提交请求,并接收回应。

    我们已经将最通用的一些命令封装在了solrServer类中了。

 

   Adding Data to Solr

  •     首先需要获得一个server的实例, 
 SolrServer server = getSolrServer();
  • 如果,你使用的是一个远程的solrServer的话呢,你或许会这样来实现getSolrServer()这个方法:      
public SolrServer getSolrServer(){
    //the instance can be reused
    return new CommonsHttpSolrServer();
}

 

  • 如果,你使用的是一个本地的solrServer的话,你或许会这样来实现getSolrServer()方法:      
public SolrServer getSolrServer(){
    //the instance can be reused
    return new EmbeddedSolrServer();
}

 

  • 如果,你在添加数据之前,想清空现有的索引,那么你可以这么做:

        

server.deleteByQuery( "*:*" );// delete everything!

 

  • 构造一个document

         

   SolrInputDocument doc1 = new SolrInputDocument();
    doc1.addField( "id", "id1", 1.0f );
    doc1.addField( "name", "doc1", 1.0f );
    doc1.addField( "price", 10 );

 

  • 构造另外一个文档,每个文档都能够被独自地提交给solr,但是,批量提交是更高效的。每一个对SolrServer的请求都是http请求,当然对于EmbeddedSolrServer来说,是不一样的。     
    SolrInputDocument doc2 = new SolrInputDocument();
    doc2.addField( "id", "id2", 1.0f );
    doc2.addField( "name", "doc2", 1.0f );
    doc2.addField( "price", 20 );

 

  • 构造一个文档的集合

        

   Collection<SolrInputDocument> docs = new  ArrayList<SolrInputDocument>();
    docs.add( doc1 );
    docs.add( doc2 );

 

  • 将documents提交给solr
server.add( docs );

 

  • 提交一个commit
 server.commit();
  • 在添加完documents后,立即做一个commit,你可以这样来写你的程序:
    UpdateRequest req = new UpdateRequest(); 
     req.setAction( UpdateRequest.ACTION.COMMIT, false, false );
    req.add( docs );
     UpdateResponse rsp = req.process( server );  

 

 

Streaming documents for an update

 

在很多的情况下,StreamingUpdateSolrServer也挺有用的。如果你使用的是solr1.4以上的版本的话,下面的代码,或许会用得着。下面的这种方法挺好用的,尤其是当你向服务器提交数据的时候。

.

 

CommonsHttpSolrServer server = new CommonsHttpSolrServer();
Iterator<SolrInputDocument> iter = new Iterator<SolrInputDocument>(){
     public boolean hasNext() {
        boolean result ;
        // set the result to true false to say if you have more documensts
        return result;
      }

      public SolrInputDocument next() {
        SolrInputDocument result = null;
        // construct a new document here and set it to result
        return result;
      }
};
server.add(iter);

 

you may also use the addBeans(Iterator<?> beansIter) method to write pojos 

Directly adding POJOs to Solr

  •    使用 java 注释创建java bean。@Field ,可以被用在域上,或者是setter方法上。如果一个域的名称跟bean的名称是不一样的,那么在java注释中填写别名,具体的,可以参照下面的域categories          
import org.apache.solr.client.solrj.beans.Field;

 public class Item {
    @Field
    String id;

    @Field("cat")
    String[] categories;

    @Field
    List<String> features;

  }

 

  • java注释也可以使用在setter方法上,如下面的例子:

        

  @Field("cat")
   public void setCategory(String[] c){
       this.categories = c;
   }

          这里应该要有一个相对的,get方法(没有加java注释的)来读取属性

  • Get an instance of server
 SolrServer server = getSolrServer();

 

  • 创建bean实例

        

   Item item = new Item();
    item.id = "one";
    item.categories =  new String[] { "aaa", "bbb", "ccc" };

 

  • 添加给solr          
server.addBean(item);

 

  • 将多个bean提交给solr

     

 List<Item> beans ;
  //add Item objects to the list
  server.addBeans(beans);   

    注意: 你可以重复使用SolrServer,这样可以提高性能。

  Reading Data from Solr

  •    获取solrserver的实例

            

SolrServer server = getSolrServer();

 

  •    构造 SolrQuery

     

    SolrQuery query = new SolrQuery();
    query.setQuery( "*:*" );
    query.addSortField( "price", SolrQuery.ORDER.asc );

 

  •    向服务器发出查询请求

    

QueryResponse rsp = server.query( query );   

 

  •    获取结果。

    

SolrDocumentList docs = rsp.getResults();

 

  •    想要以javabean的方式获取结果,那么这个javabean必须像之前的例子一样有java注释。
     List<Item> beans = rsp.getBeans(Item.class);
    
     

    高级用法

       solrJ 提供了一组API,来帮助我们创建查询,下面是一个faceted query的例子。

 SolrServer server = getSolrServer();
  SolrQuery solrQuery = new  SolrQuery().
                setQuery("ipod").
                setFacet(true).
                setFacetMinCount(1).
                setFacetLimit(8).
                addFacetField("category").
                addFacetField("inStock");  
  QueryResponse rsp = server.query(solrQuery);

 所有的 setter/add 方法都是返回它自己本身的实例,所以就像你所看到的一样,上面的用法是链式的。

分享到:
评论
6 楼 mxsfengg 2009-06-10  
qipei 写道
引用

刚刚我也试了一下,还是没有乱码。没有对汉字URLEncoder,Tomcat的URLEncoder是“UTF-8”,记得solr好像是默认UTF-8试试,说不定会有意外。


我之前也是 “UTF8” 这样 应该可以
1. 我现在如果不把Tomcat的URLEncoder设置成“GBK”的话, 如果从浏览器地址栏直接输入中文条件来查询会不会有乱码问题?

2. 另外请教你一个问题:
   在拼url查询的时候 对于短语应该用双引号包围,但是我如果不包围,查询结果有时会不一样,不知道solr 是怎么处理参数的?比如:
   http://xxxxx:xx/xx/select?q=word:"Hello boy"(不一定是HELLO BOY, 比如一句话)
   http://xxxxx:xx/xx/select?q=word:Hello boy
如果是单词:
    直接 http://xxxxx:xx/xx/select?q=word:Hello 这样写
   一直没有弄明白这个。。


呵,可以就好。
1 . 在地址栏直接输入是会乱码的,之所以我们使用solrj不用URLEncoder是因为solrj已经做了这些工作了。代码好像在ClientUtils这个类里面。
2 . 用引号括起来那就是“短语查询”,也就是一定匹配到 Hello boy才会到结果集, 没有用引号的话,Hello boy就会构建成为布尔查询,也就是说,同时有Hello和boy的记录都可以被匹配,当然那个布尔查询可以是AND 也可以是OR的关系。^_^
5 楼 qipei 2009-06-10  
引用

刚刚我也试了一下,还是没有乱码。没有对汉字URLEncoder,Tomcat的URLEncoder是“UTF-8”,记得solr好像是默认UTF-8试试,说不定会有意外。


我之前也是 “UTF8” 这样 应该可以
1. 我现在如果不把Tomcat的URLEncoder设置成“GBK”的话, 如果从浏览器地址栏直接输入中文条件来查询会不会有乱码问题?

2. 另外请教你一个问题:
   在拼url查询的时候 对于短语应该用双引号包围,但是我如果不包围,查询结果有时会不一样,不知道solr 是怎么处理参数的?比如:
   http://xxxxx:xx/xx/select?q=word:"Hello boy"(不一定是HELLO BOY, 比如一句话)
   http://xxxxx:xx/xx/select?q=word:Hello boy
如果是单词:
    直接 http://xxxxx:xx/xx/select?q=word:Hello 这样写
   一直没有弄明白这个。。

4 楼 mxsfengg 2009-06-10  
qipei 写道
mxsfengg 写道
qipei 写道
solrj query的时候如果参数是中文 会乱码  你怎么解决的?

我现在使用的时候没有遇到乱码的问题啊,你 遇到的是什么情况,给段代码吧。..

//get Solr Server
public static SolrServer getSolrServer() {
      try {
         return new CommonsHttpSolrServer(new URL(solrUrl));
      } catch (MalformedURLException e) {
         throw new SolrException("can not connect to solr server", e);
      }
   }

//这个方法是Util理得方法 进行查询 返回JSON格式 的 数据
 public static JSONArray queryData(SolrQuery query) {
      SolrDocumentList queryResult = null;
      JSONArray jsonArray = new JSONArray();
      try {
         SolrServer server = getSolrServer();
         QueryResponse qr = server.query(query);
         queryResult = qr.getResults();
      } catch (SolrServerException e) {
         throw new SolrException("error when querying data", e);
      }
      for (Iterator<SolrDocument> it = queryResult.iterator(); it.hasNext(); ) {
         SolrDocument document = it.next();
         JSONObject jsonObject = new JSONObject();
         for(Iterator<Entry<String, Object>> it2 = document.iterator(); it2.hasNext();) {
            Entry<String, Object> entry = it2.next();
            try {
               jsonObject.put(entry.getKey(), entry.getValue());
            } catch (JSONException e) {
               throw new SolrException("can not convert solr data to json", e);
            }
         }
         jsonArray.put(jsonObject);
      }
      return jsonArray;
   }


//调用上面查询的方法

public void autoTranslate(Long sourceLocId, Long targetLocId) {
      		。
		。
		。
		。
		。

               SolrQuery query = new SolrQuery();
            String queryStr = "sourceLang:" + sourceLoc.getLanguage().getLanguage ().getLanguageValue()
                     + " AND targetLang:" + targetLoc.getLanguage().getLanguage().getLanguageValue()
                     + " AND sourceValue:" + SolrUtil.filterStringValue(locContent.getContent());
		// SolrUtil.filterStringValue(locContent.getContent()); locContent.getContent() 是从数据库里得到的数据 可能包含中文 数据库编码是(UTF8)
		// SolrUtil.filterStringValue 是对数据库里的数据进行过滤 把一些特殊字符转义  在这里也没有进行什么编码
		
               query.setQuery(queryStr); //queryStr 我用URLEncoder 把汉字编码成 “%xx”的形式后 
 //进行查询,在把queryStr传给solrj后, solrj 会再将 %给转义了 但是我不需要再将%转义

		//我的服务器是 tomcat , tomcat的URIEncoder 是 "GBK"
		// 我尝试通过字符串编码 把queryStr 从UTF8到GBK, GB2312, IS08859-1之间转换 结果在solrj发出的URL里汉字还是乱码
               query.setFields("*,score");
               query.setRows(1);
               JSONArray jsonArray = SolrUtil.queryData(query);
               。
		。
		。
		。
		。
         
         
      }


1. queryData 发送的请求中 q后面得汉字参数是 乱码

2. Solrj 应该是 用 httpClient 发请求吧? httpClient 默认编码是 Iso8859-1 我是不是应该设置httpclient的编码, 但是通过SOLRJ怎么设置呢?


刚刚我也试了一下,还是没有乱码。没有对汉字URLEncoder,Tomcat的URLEncoder是“UTF-8”,记得solr好像是默认UTF-8试试,说不定会有意外。
3 楼 qipei 2009-06-10  
mxsfengg 写道
qipei 写道
solrj query的时候如果参数是中文 会乱码  你怎么解决的?

我现在使用的时候没有遇到乱码的问题啊,你 遇到的是什么情况,给段代码吧。..

//get Solr Server
public static SolrServer getSolrServer() {
      try {
         return new CommonsHttpSolrServer(new URL(solrUrl));
      } catch (MalformedURLException e) {
         throw new SolrException("can not connect to solr server", e);
      }
   }

//这个方法是Util理得方法 进行查询 返回JSON格式 的 数据
 public static JSONArray queryData(SolrQuery query) {
      SolrDocumentList queryResult = null;
      JSONArray jsonArray = new JSONArray();
      try {
         SolrServer server = getSolrServer();
         QueryResponse qr = server.query(query);
         queryResult = qr.getResults();
      } catch (SolrServerException e) {
         throw new SolrException("error when querying data", e);
      }
      for (Iterator<SolrDocument> it = queryResult.iterator(); it.hasNext(); ) {
         SolrDocument document = it.next();
         JSONObject jsonObject = new JSONObject();
         for(Iterator<Entry<String, Object>> it2 = document.iterator(); it2.hasNext();) {
            Entry<String, Object> entry = it2.next();
            try {
               jsonObject.put(entry.getKey(), entry.getValue());
            } catch (JSONException e) {
               throw new SolrException("can not convert solr data to json", e);
            }
         }
         jsonArray.put(jsonObject);
      }
      return jsonArray;
   }


//调用上面查询的方法

public void autoTranslate(Long sourceLocId, Long targetLocId) {
      		。
		。
		。
		。
		。

               SolrQuery query = new SolrQuery();
            String queryStr = "sourceLang:" + sourceLoc.getLanguage().getLanguage ().getLanguageValue()
                     + " AND targetLang:" + targetLoc.getLanguage().getLanguage().getLanguageValue()
                     + " AND sourceValue:" + SolrUtil.filterStringValue(locContent.getContent());
		// SolrUtil.filterStringValue(locContent.getContent()); locContent.getContent() 是从数据库里得到的数据 可能包含中文 数据库编码是(UTF8)
		// SolrUtil.filterStringValue 是对数据库里的数据进行过滤 把一些特殊字符转义  在这里也没有进行什么编码
		
               query.setQuery(queryStr); //queryStr 我用URLEncoder 把汉字编码成 “%xx”的形式后 
 //进行查询,在把queryStr传给solrj后, solrj 会再将 %给转义了 但是我不需要再将%转义

		//我的服务器是 tomcat , tomcat的URIEncoder 是 "GBK"
		// 我尝试通过字符串编码 把queryStr 从UTF8到GBK, GB2312, IS08859-1之间转换 结果在solrj发出的URL里汉字还是乱码
               query.setFields("*,score");
               query.setRows(1);
               JSONArray jsonArray = SolrUtil.queryData(query);
               。
		。
		。
		。
		。
         
         
      }


1. queryData 发送的请求中 q后面得汉字参数是 乱码

2. Solrj 应该是 用 httpClient 发请求吧? httpClient 默认编码是 Iso8859-1 我是不是应该设置httpclient的编码, 但是通过SOLRJ怎么设置呢?
2 楼 mxsfengg 2009-06-08  
qipei 写道
solrj query的时候如果参数是中文 会乱码  你怎么解决的?

我现在使用的时候没有遇到乱码的问题啊,你 遇到的是什么情况,给段代码吧。..
1 楼 qipei 2009-06-08  
solrj query的时候如果参数是中文 会乱码  你怎么解决的?

相关推荐

Global site tag (gtag.js) - Google Analytics