Solr 入门实战(4)--Java 操作 Solr
本文主要介绍使用 Java 来操作 Solr,文中所使用到的软件版本:Java 1.8.0_191、Solr 8.9.0。
1、定义 Schema 信息
假设一个描述诗人信息的文档包含如下字段:
字段 | 描述 |
id | 唯一主键 |
age | 年龄 |
name | 姓名 |
poems | 诗歌 |
about | 简介 |
success | 成就 |
定义的 schema 信息如下:
<field name="about" type="text_ik" uninvertible="true" indexed="true" stored="true"/> <field name="age" type="pint" uninvertible="true" indexed="true" stored="true"/> <field name="content" type="text_ik" uninvertible="true" indexed="true" stored="true" multiValued="true"/> <field name="id" type="string" multiValued="false" indexed="true" required="true" stored="true"/> <field name="name" type="text_ik" uninvertible="true" indexed="true" stored="true"/> <field name="poems" type="text_ik" uninvertible="true" indexed="true" stored="true"/> <field name="success" type="text_ik" uninvertible="true" indexed="true" stored="true"/>
2、Java 操作 Solr
2.1、引入依赖
<dependency> <groupId>org.apache.solr</groupId> <artifactId>solr-solrj</artifactId> <version>8.9.0</version> </dependency> <dependency> <groupId>org.apache.solr</groupId> <artifactId>solr-core</artifactId> <version>8.9.0</version> </dependency>
2.2、编写 demo
2.2.1、增加/更新文档
@Test public void update() throws IOException, SolrServerException { SolrInputDocument document = new SolrInputDocument(); document.addField("id", "123456"); document.addField("age", 30); document.addField("name", "李白2"); document.addField("poems", "望庐山瀑布"); document.addField("about", "字太白"); document.addField("success", "创造了古代浪漫主义文学高峰、歌行体和七绝达到后人难及的高度"); SolrInputDocument document2 = new SolrInputDocument(); document2.addField("id", "123457"); document2.addField("age", 31); document2.addField("name", "杜甫"); document2.addField("poems", "望岳"); document2.addField("about", "字子美"); document2.addField("success", "唐代伟大的现实主义文学作家,唐诗思想艺术的集大成者"); solrClient.add(coreName, document); solrClient.add(coreName, document2); solrClient.commit(coreName, true,true); }
还可以通过实体类来增加/更新文档:
@Test
public void update2() throws IOException, SolrServerException {
PoetInfo info = new PoetInfo("123456", 40, "李白", "望庐山瀑布", "字太白", "创造了古代浪漫主义文学高峰、歌行体和七绝达到后人难及的高度");
solrClient.addBean(coreName, info);
solrClient.commit(coreName, true,true);
}
2.2.2、查询文档
/** * 通过 MapSolrParams 查询 */ @Test public void query() throws IOException, SolrServerException { Map<String, String> map = new HashMap<>(); //查询条件 map.put("q", "*:*"); //要显示的内容 map.put("fl", "id,age,name,poems"); //排序方式 map.put("sort", "id asc"); MapSolrParams solrParams = new MapSolrParams(map); QueryResponse queryResponse = solrClient.query(coreName, solrParams); SolrDocumentList documents = queryResponse.getResults(); logger.info("查询到{}个文档!", documents.getNumFound()); for (SolrDocument document : documents) { String id = (String)document.getFieldValue("id"); Integer age = (Integer)document.getFieldValue("age"); String name = (String)document.getFieldValue("name"); String poems = (String)document.getFieldValue("poems"); logger.info("id={},age={},name={},poems={}", id, age, name, poems); } } /** * 通过 solrQuery 查询 */ @Test public void query2() throws IOException, SolrServerException { SolrQuery solrQuery = new SolrQuery("*:*"); solrQuery.addField("id"); solrQuery.addField("age"); solrQuery.addField("name"); solrQuery.addField("poems"); solrQuery.addSort("id", SolrQuery.ORDER.asc); //设置返回的行数 solrQuery.setRows(10); QueryResponse queryResponse = solrClient.query(coreName, solrQuery); SolrDocumentList documents = queryResponse.getResults(); logger.info("查询到{}个文档!", documents.getNumFound()); for (SolrDocument document : documents) { String id = (String)document.getFieldValue("id"); Integer age = (Integer)document.getFieldValue("age"); String name = (String)document.getFieldValue("name"); String poems = (String)document.getFieldValue("poems"); logger.info("id={},age={},name={},poems={}", id, age, name, poems); } } /** * 查询返回实例类对象 */ @Test public void query3() throws IOException, SolrServerException { SolrQuery solrQuery = new SolrQuery("*:*"); solrQuery.addField("id"); solrQuery.addField("age"); solrQuery.addField("name"); solrQuery.addField("poems"); solrQuery.addField("about"); solrQuery.addField("success"); solrQuery.addSort("id", SolrQuery.ORDER.asc); //设置返回的行数 solrQuery.setRows(10); QueryResponse queryResponse = solrClient.query(coreName, solrQuery); List<PoetInfo> list = queryResponse.getBeans(PoetInfo.class); logger.info("查询到{}个文档!", list.size()); for (PoetInfo info : list) { logger.info(info.toString()); } }
2.2.3、删除文档
/** * 根据id删除文档 */ @Test public void delete() throws IOException, SolrServerException { solrClient.deleteById(coreName, "123456"); solrClient.commit(coreName, true,true); } /** * 根据查询删除文档 */ @Test public void delete2() throws IOException, SolrServerException { solrClient.deleteByQuery(coreName, "name:杜甫"); solrClient.commit(coreName, true,true); }
2.2.4、完整代码
package com.abc.demo.general.solr; import org.apache.solr.client.solrj.beans.Field; public class PoetInfo { @Field private String id; @Field private Integer age; @Field private String name; @Field private String poems; @Field private String about; @Field private String success; public PoetInfo() { } public PoetInfo(String id, Integer age, String name, String poems, String about, String success) { this.id = id; this.age = age; this.name = name; this.poems = poems; this.about = about; this.success = success; } @Override public String toString() { return "Info{" + "id='" + id + '\'' + ", age=" + age + ", name='" + name + '\'' + ", poems='" + poems + '\'' + ", about='" + about + '\'' + ", success='" + success + '\'' + '}'; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAbout() { return about; } public void setAbout(String about) { this.about = about; } public String getSuccess() { return success; } public void setSuccess(String success) { this.success = success; } }
package com.abc.demo.general.solr; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.params.MapSolrParams; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; public class SolrCase { private static Logger logger = LoggerFactory.getLogger(SolrCase.class); private HttpSolrClient solrClient; private String coreName = "new_core"; @Before public void before() { solrClient = new HttpSolrClient.Builder("http://10.49.196.10:8983/solr") .withConnectionTimeout(10000) .withSocketTimeout(60000) .build(); } @After public void after() throws IOException { solrClient.close(); } @Test public void update() throws IOException, SolrServerException { SolrInputDocument document = new SolrInputDocument(); document.addField("id", "123456"); document.addField("age", 30); document.addField("name", "李白2"); document.addField("poems", "望庐山瀑布"); document.addField("about", "字太白"); document.addField("success", "创造了古代浪漫主义文学高峰、歌行体和七绝达到后人难及的高度"); SolrInputDocument document2 = new SolrInputDocument(); document2.addField("id", "123457"); document2.addField("age", 31); document2.addField("name", "杜甫"); document2.addField("poems", "望岳"); document2.addField("about", "字子美"); document2.addField("success", "唐代伟大的现实主义文学作家,唐诗思想艺术的集大成者"); solrClient.add(coreName, document); solrClient.add(coreName, document2); solrClient.commit(coreName, true,true); } @Test public void update2() throws IOException, SolrServerException { PoetInfo info = new PoetInfo("123456", 40, "李白", "望庐山瀑布", "字太白", "创造了古代浪漫主义文学高峰、歌行体和七绝达到后人难及的高度"); solrClient.addBean(coreName, info); solrClient.commit(coreName, true,true); } /** * 通过 MapSolrParams 查询 */ @Test public void query() throws IOException, SolrServerException { Map<String, String> map = new HashMap<>(); //查询条件 map.put("q", "*:*"); //要显示的内容 map.put("fl", "id,age,name,poems"); //排序方式 map.put("sort", "id asc"); MapSolrParams solrParams = new MapSolrParams(map); QueryResponse queryResponse = solrClient.query(coreName, solrParams); SolrDocumentList documents = queryResponse.getResults(); logger.info("查询到{}个文档!", documents.getNumFound()); for (SolrDocument document : documents) { String id = (String)document.getFieldValue("id"); Integer age = (Integer)document.getFieldValue("age"); String name = (String)document.getFieldValue("name"); String poems = (String)document.getFieldValue("poems"); logger.info("id={},age={},name={},poems={}", id, age, name, poems); } } /** * 通过 solrQuery 查询 */ @Test public void query2() throws IOException, SolrServerException { SolrQuery solrQuery = new SolrQuery("*:*"); solrQuery.addField("id"); solrQuery.addField("age"); solrQuery.addField("name"); solrQuery.addField("poems"); solrQuery.addSort("id", SolrQuery.ORDER.asc); //设置返回的行数 solrQuery.setRows(10); QueryResponse queryResponse = solrClient.query(coreName, solrQuery); SolrDocumentList documents = queryResponse.getResults(); logger.info("查询到{}个文档!", documents.getNumFound()); for (SolrDocument document : documents) { String id = (String)document.getFieldValue("id"); Integer age = (Integer)document.getFieldValue("age"); String name = (String)document.getFieldValue("name"); String poems = (String)document.getFieldValue("poems"); logger.info("id={},age={},name={},poems={}", id, age, name, poems); } } /** * 查询返回实例类对象 */ @Test public void query3() throws IOException, SolrServerException { SolrQuery solrQuery = new SolrQuery("*:*"); solrQuery.addField("id"); solrQuery.addField("age"); solrQuery.addField("name"); solrQuery.addField("poems"); solrQuery.addField("about"); solrQuery.addField("success"); solrQuery.addSort("id", SolrQuery.ORDER.asc); //设置返回的行数 solrQuery.setRows(10); QueryResponse queryResponse = solrClient.query(coreName, solrQuery); List<PoetInfo> list = queryResponse.getBeans(PoetInfo.class); logger.info("查询到{}个文档!", list.size()); for (PoetInfo info : list) { logger.info(info.toString()); } } /** * 根据id删除文档 */ @Test public void delete() throws IOException, SolrServerException { solrClient.deleteById(coreName, "123456"); solrClient.commit(coreName, true,true); } /** * 根据查询删除文档 */ @Test public void delete2() throws IOException, SolrServerException { solrClient.deleteByQuery(coreName, "name:杜甫"); solrClient.commit(coreName, true,true); } }
3、Java 操作 SolrCloud
Java 操作 SolrCloud 与 Java 操作 Solr 很类似,主要区别有:
1、连接使用的类不同,连接 Solr 使用的是 HttpSolrClient,连接 SolrColud 使用的是 CloudHttp2SolrClient。
2、API 针对的操作对象不同,Solr 针对的是 core,SolrCloud 针对的是 collection。
3.1、引入依赖
<dependency> <groupId>org.apache.solr</groupId> <artifactId>solr-solrj</artifactId> <version>8.9.0</version> </dependency> <dependency> <groupId>org.apache.solr</groupId> <artifactId>solr-core</artifactId> <version>8.9.0</version> </dependency>
3.2、编写 demo
3.2.1、增加/更新文档
@Test public void update() throws IOException, SolrServerException { SolrInputDocument document = new SolrInputDocument(); document.addField("id", "123456"); document.addField("age", 30); document.addField("name", "李白2"); document.addField("poems", "望庐山瀑布"); document.addField("about", "字太白"); document.addField("success", "创造了古代浪漫主义文学高峰、歌行体和七绝达到后人难及的高度"); SolrInputDocument document2 = new SolrInputDocument(); document2.addField("id", "123457"); document2.addField("age", 31); document2.addField("name", "杜甫"); document2.addField("poems", "望岳"); document2.addField("about", "字子美"); document2.addField("success", "唐代伟大的现实主义文学作家,唐诗思想艺术的集大成者"); solrClient.add(collection, document); solrClient.add(collection, document2); solrClient.commit(collection, true,true); }
还可以通过实体类来增加/更新文档:
@Test public void update2() throws IOException, SolrServerException { PoetInfo info = new PoetInfo("123456", 40, "李白", "望庐山瀑布", "字太白", "创造了古代浪漫主义文学高峰、歌行体和七绝达到后人难及的高度"); solrClient.addBean(collection, info); solrClient.commit(collection, true,true); }
3.2.2、查询文档
/** * 通过 MapSolrParams 查询 */ @Test public void query() throws IOException, SolrServerException { Map<String, String> map = new HashMap<>(); //查询条件 map.put("q", "*:*"); //要显示的内容 map.put("fl", "id,age,name,poems"); //排序方式 map.put("sort", "id asc"); MapSolrParams solrParams = new MapSolrParams(map); QueryResponse queryResponse = solrClient.query(collection, solrParams); SolrDocumentList documents = queryResponse.getResults(); logger.info("查询到{}个文档!", documents.getNumFound()); for (SolrDocument document : documents) { String id = (String)document.getFieldValue("id"); Integer age = (Integer)document.getFieldValue("age"); String name = (String)document.getFieldValue("name"); String poems = (String)document.getFieldValue("poems"); logger.info("id={},age={},name={},poems={}", id, age, name, poems); } } /** * 通过 solrQuery 查询 */ @Test public void query2() throws IOException, SolrServerException { SolrQuery solrQuery = new SolrQuery("*:*"); solrQuery.addField("id"); solrQuery.addField("age"); solrQuery.addField("name"); solrQuery.addField("poems"); solrQuery.addSort("id", SolrQuery.ORDER.asc); //设置返回的行数 solrQuery.setRows(10); QueryResponse queryResponse = solrClient.query(collection, solrQuery); SolrDocumentList documents = queryResponse.getResults(); logger.info("查询到{}个文档!", documents.getNumFound()); for (SolrDocument document : documents) { String id = (String)document.getFieldValue("id"); Integer age = (Integer)document.getFieldValue("age"); String name = (String)document.getFieldValue("name"); String poems = (String)document.getFieldValue("poems"); logger.info("id={},age={},name={},poems={}", id, age, name, poems); } } /** * 查询返回实例类对象 */ @Test public void query3() throws IOException, SolrServerException { SolrQuery solrQuery = new SolrQuery("*:*"); solrQuery.addField("id"); solrQuery.addField("age"); solrQuery.addField("name"); solrQuery.addField("poems"); solrQuery.addField("about"); solrQuery.addField("success"); solrQuery.addSort("id", SolrQuery.ORDER.asc); //设置返回的行数 solrQuery.setRows(10); QueryResponse queryResponse = solrClient.query(collection, solrQuery); List<PoetInfo> list = queryResponse.getBeans(PoetInfo.class); logger.info("查询到{}个文档!", list.size()); for (PoetInfo info : list) { logger.info(info.toString()); } }
3.2.3、删除文档
/** * 根据id删除文档 */ @Test public void delete() throws IOException, SolrServerException { solrClient.deleteById(collection, "123457"); solrClient.commit(collection, true,true); } /** * 根据查询删除文档 */ @Test public void delete2() throws IOException, SolrServerException { solrClient.deleteByQuery(collection, "name:杜甫"); solrClient.commit(collection, true,true); }
3.2.4、完整代码
package com.abc.demo.general.solr; import org.apache.solr.client.solrj.beans.Field; public class PoetInfo { @Field private String id; @Field private Integer age; @Field private String name; @Field private String poems; @Field private String about; @Field private String success; public PoetInfo() { } public PoetInfo(String id, Integer age, String name, String poems, String about, String success) { this.id = id; this.age = age; this.name = name; this.poems = poems; this.about = about; this.success = success; } @Override public String toString() { return "Info{" + "id='" + id + '\'' + ", age=" + age + ", name='" + name + '\'' + ", poems='" + poems + '\'' + ", about='" + about + '\'' + ", success='" + success + '\'' + '}'; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAbout() { return about; } public void setAbout(String about) { this.about = about; } public String getSuccess() { return success; } public void setSuccess(String success) { this.success = success; } }
package com.abc.demo.general.solr; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.CloudHttp2SolrClient; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.params.MapSolrParams; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class CloudSolrCase { private static Logger logger = LoggerFactory.getLogger(CloudSolrCase.class); private CloudHttp2SolrClient solrClient; private String collection = "collection-1"; @Before public void before() { List<String> urls = new ArrayList<>(); urls.add("http://10.49.196.10:8983/solr"); urls.add("http://10.49.196.11:8983/solr"); urls.add("http://10.49.196.12:8983/solr"); solrClient = new CloudHttp2SolrClient.Builder(urls).build(); } @After public void after() throws IOException { solrClient.close(); } @Test public void update() throws IOException, SolrServerException { SolrInputDocument document = new SolrInputDocument(); document.addField("id", "123456"); document.addField("age", 30); document.addField("name", "李白2"); document.addField("poems", "望庐山瀑布"); document.addField("about", "字太白"); document.addField("success", "创造了古代浪漫主义文学高峰、歌行体和七绝达到后人难及的高度"); SolrInputDocument document2 = new SolrInputDocument(); document2.addField("id", "123457"); document2.addField("age", 31); document2.addField("name", "杜甫"); document2.addField("poems", "望岳"); document2.addField("about", "字子美"); document2.addField("success", "唐代伟大的现实主义文学作家,唐诗思想艺术的集大成者"); solrClient.add(collection, document); solrClient.add(collection, document2); solrClient.commit(collection, true,true); } @Test public void update2() throws IOException, SolrServerException { PoetInfo info = new PoetInfo("123456", 40, "李白", "望庐山瀑布", "字太白", "创造了古代浪漫主义文学高峰、歌行体和七绝达到后人难及的高度"); solrClient.addBean(collection, info); solrClient.commit(collection, true,true); } /** * 通过 MapSolrParams 查询 */ @Test public void query() throws IOException, SolrServerException { Map<String, String> map = new HashMap<>(); //查询条件 map.put("q", "*:*"); //要显示的内容 map.put("fl", "id,age,name,poems"); //排序方式 map.put("sort", "id asc"); MapSolrParams solrParams = new MapSolrParams(map); QueryResponse queryResponse = solrClient.query(collection, solrParams); SolrDocumentList documents = queryResponse.getResults(); logger.info("查询到{}个文档!", documents.getNumFound()); for (SolrDocument document : documents) { String id = (String)document.getFieldValue("id"); Integer age = (Integer)document.getFieldValue("age"); String name = (String)document.getFieldValue("name"); String poems = (String)document.getFieldValue("poems"); logger.info("id={},age={},name={},poems={}", id, age, name, poems); } } /** * 通过 solrQuery 查询 */ @Test public void query2() throws IOException, SolrServerException { SolrQuery solrQuery = new SolrQuery("*:*"); solrQuery.addField("id"); solrQuery.addField("age"); solrQuery.addField("name"); solrQuery.addField("poems"); solrQuery.addSort("id", SolrQuery.ORDER.asc); //设置返回的行数 solrQuery.setRows(10); QueryResponse queryResponse = solrClient.query(collection, solrQuery); SolrDocumentList documents = queryResponse.getResults(); logger.info("查询到{}个文档!", documents.getNumFound()); for (SolrDocument document : documents) { String id = (String)document.getFieldValue("id"); Integer age = (Integer)document.getFieldValue("age"); String name = (String)document.getFieldValue("name"); String poems = (String)document.getFieldValue("poems"); logger.info("id={},age={},name={},poems={}", id, age, name, poems); } } /** * 查询返回实例类对象 */ @Test public void query3() throws IOException, SolrServerException { SolrQuery solrQuery = new SolrQuery("*:*"); solrQuery.addField("id"); solrQuery.addField("age"); solrQuery.addField("name"); solrQuery.addField("poems"); solrQuery.addField("about"); solrQuery.addField("success"); solrQuery.addSort("id", SolrQuery.ORDER.asc); //设置返回的行数 solrQuery.setRows(10); QueryResponse queryResponse = solrClient.query(collection, solrQuery); List<PoetInfo> list = queryResponse.getBeans(PoetInfo.class); logger.info("查询到{}个文档!", list.size()); for (PoetInfo info : list) { logger.info(info.toString()); } } /** * 根据id删除文档 */ @Test public void delete() throws IOException, SolrServerException { solrClient.deleteById(collection, "123457"); solrClient.commit(collection, true,true); } /** * 根据查询删除文档 */ @Test public void delete2() throws IOException, SolrServerException { solrClient.deleteByQuery(collection, "name:杜甫"); solrClient.commit(collection, true,true); } }