solr学习(六):使用自定义int/long类型主键

本文介绍如何在Solr中自定义主键字段,并通过示例演示如何将默认的字符串类型主键更改为整型的article_id,同时解决在此过程中可能遇到的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求分析:

我不想使用solr默认的主键id,我想换成其他的,比如我的文章id为article_id,我想让article_id作为主键。

而且,我的主键是int类型,而solr的主键默认是string类型,我们还需要修改,修改后,还会报错,我们还需要来解决报错问题。

实践:

第一步:

我们需要打开C:\data\solr\collection1\conf\schema.xml

然后我们找到id的主键field

1
2
  < field name = "id" type = "String" indexed = "true" stored = "true" required = "true" multiValued = "false" />

然后我们修改为

1
2
  < field name = "article_id" type = "int" indexed = "true" stored = "true" required = "true" multiValued = "false" />

不光是要修改name值,还需要修改type值。

第二步:

我们在schema.xml中找到

1
2
  < uniqueKey >id</ uniqueKey >

我们修改为:

1
2
  < uniqueKey >article_id</ uniqueKey >

这样还不行,因为运行的时候,还是会报错,所以,我们还需要修改

C:\data\solr\collection1\conf\solrconfig.xml

找到这个位置:

1
2
3
4
5
6
7
< searchComponent name = "elevator" class = "solr.QueryElevationComponent" >
 
     < str name = "queryFieldType" >String</ str >
     < str name = "config-file" >elevate.xml</ str >
   </ searchComponent >

将其注释掉!

会变成这个样子:

1
2
3
4
5
6
7
8
<!--
   <searchComponent name="elevator" class="solr.QueryElevationComponent" >
 
     <str name="queryFieldType">String</str>
     <str name="config-file">elevate.xml</str>
   </searchComponent>
-->

然后,我们修改我们的test.class中的测试类,将id改为article_id

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Test
     public void testAddDocument () throws Exception {
           
            SolrServer solrServer = new HttpSolrServer( "http://localhost:8080/solr/collection1" );
           
          
            //创建一个文档对象SolrInputDocument
            SolrInputDocument document = new SolrInputDocument();
            //向文档中添加域,必须有id域,域的名称必须在scheme.xml中定义
            document.addField( "article_id" , "2000" );
            document.addField( "article_title" , "java是世界上最好的语言" );
         
            //把文档对象写入索引库
            solrServer.add(document);
             
            //提交(两种方式都要进行提交操作)
            solrServer.commit();
 
        }

我们junit运行一下,然后我们访问localhost:8080/solr,进行query搜索,查看一下是否id变为了int类型

图片.png

这样就测试成功了!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值