Solr添加文档到索引

solr添加文档非常方便,不用像Lucene那样一个一个添加Field,省去了很多的麻烦下面看操作

方法一:

private static String URI = "http://localhost:8080/solr/";
 
     private CommonsHttpSolrServer httpSolrServer = null;
 
     @Before
     public void init() {
         try {
             httpSolrServer = new CommonsHttpSolrServer(URI);
         } catch (MalformedURLException e) {
             e.printStackTrace();
         }
     }
 
     @Test
     public void test1() {
         try {
             SolrInputDocument document = new SolrInputDocument();
             document.addField("id", "1");
             document.addField("news_title", "这是我的第一个solr程序");
             document.addField("news_content", "希望能够运行起来");
             httpSolrServer.add(document);
             httpSolrServer.commit();
         } catch (SolrServerException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         }

     }

Note:id为唯一,不可重复,如果重复,solr会自动将索引中id相同的元素更新为现在的属性
域的名称可以在schema.xml的Field中设置,默认的有很多Field,我们也可以使用默认的

   <field name="news_title" type="textComplex" indexed="true" stored="true" />
   <field name="news_content" type="textComplex" indexed="true" sotred="true" />

 

方法2:直接添加对象

2.1 定义对象

package com.solr.entity;
 
 import org.apache.solr.client.solrj.beans.Field;
 
 public class News {
     private String id;
     private String title;
     private String content;
 
     public News(){}
     
     public News(String id, String title, String content) {
         this.id = id;
         this.title = title;
         this.content = content;
     }
 
     public String getId() {
         return id;
     }
 
     @Field
     public void setId(String id) {
         this.id = id;
     }
 
     public String getTitle() {
         return title;
     }
 
     @Field("news_title")
     public void setTitle(String title) {
         this.title = title;
     }
 
     public String getContent() {
         return content;
     }
 
     @Field("news_content")
     public void setContent(String content) {
         this.content = content;
     }
 
 }

2.2 添加对象到索引

@Test
     public void test2() {
         try {
             List<News> list = new ArrayList<News>();
             News news1 = new News("2", "title2", "content2");
             list.add(news1);
             News news2 = new News("3", "title3", "content3");
             list.add(news2);
 
             httpSolrServer.addBeans(list);
             httpSolrServer.commit();
         } catch (SolrServerException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }

Note:如果对象的某个域里面的属性为数组,我们需要在schema.xml的Field中设置 multiValued="true"


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值