继上一篇,solr启动成功后,使用java来简单操作下solr的数据,也就是solr中的Document。
首先我们创建一个core来用于测试,创建core的方式见博文 Apache solr入门中的创建core章节。
- 这里我们创建一个test_core用于来测试
- 在 managed-schema文件中添加两个简单的字段(test_id, test_name)用于测试,如下:(也可以直接在界面操作添加字段)
<field name="test_id" type="string" uninvertible="true" indexed="true" required="true" stored="true"/>
<field name="test_name" type="string" uninvertible="true" indexed="true" stored="true"/>
- 修改默认的主键为我们新建的test_id字段,修改managed-schema文件中的内容如下:(这个步骤非必须,只是在这里记录下怎么修改sor的主键为自定义主键。自定义主键字段类型必须为string)
<!-- 定义主键字段 -->
<uniqueKey>test_id</uniqueKey>
<!-- id字段是solr默认的主键字段 -->
<field name="id" type="string" multiValued="false" indexed="true" required="false" stored="false"/>
- 重启solr,让新添加的字段生效
- 先添加maven依赖
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>7.7.2</version>
</dependency>
添加/更新Document
操作很简单,这里就直接附上代码,如下:(更新索引没有特殊的update操作,只需要保证id是已存在的,直接执行add操作即可更新对应的数据)
public static void addDocument(){
SolrInputDocument solrDocument = new SolrInputDocument();
solrDocument.addField("test_id","1");
solrDocument.addField("test_name", "张三");
HttpSolrClient client = new HttpSolrClient.Builder("http://192.168.94.123:8983/solr/test_core").build();
try {
client.add(solrDocument);
client.commit();
client.close();
System.out.println("添加成功");
} catch (Exception e) {
e.printStackTrace();
}
}
删除Document
public static void deleteDocument(){
HttpSolrClient client = new HttpSolrClient.Builder("http://192.168.94.123:8983/solr/test_core").build();
try {
client.deleteById("1");
client.commit();
client.close();
System.out.println("删除成功");
} catch (Exception e) {
e.printStackTrace();
}
}
查询数据
参数数据就很简单了,主要用到的类是SolrQuery,然后就是设置过滤条件了,可以参见之前的博文java操作solr----双core关联查询,这里虽然讲的是双core关联查询,但是单core查询也是如此,更简单了,自己动动脑筋想一下,印象更深刻哦