当前位置:网站首页>04_ Use of solrj7.3 of solr7.3
04_ Use of solrj7.3 of solr7.3
2022-07-05 14:12:00 【Full stack programmer webmaster】
SolrJ is an API that makes it easy for Java applications to talk to Solr. SolrJ hides a lot of the details of connecting to Solr and allows your application to interact with Solr with simple high-level methods.
The center of SolrJ is the org.apache.solr.client.solrj package, which contains just five main classes. Begin by creating a SolrClient, which represents the Solr instance you want to use. Then send SolrRequests or SolrQuerys and get back SolrResponses.
SolrClient is abstract, so to connect to a remote Solr instance, you’ll actually create an instance of either HttpSolrClient, or CloudSolrClient. Both communicate with Solr via HTTP, the difference is that HttpSolrClient is configured using an explicit Solr URL, while CloudSolrClient is configured using the zkHost String for a SolrCloud cluster.
Single node Solr client
String urlString = "http://localhost:8983/solr/techproducts";
SolrClient solr = new HttpSolrClient.Builder(urlString).build();SolrCloud client
// Using a ZK Host String
String zkHostString = "zkServerA:2181,zkServerB:2181,zkServerC:2181/solr";
SolrClient solr = new CloudSolrClient.Builder().withZkHost(zkHostString).build();
// Using already running Solr nodes
SolrClient solr = new CloudSolrClient.Builder().withSolrUrl("http://localhost:8983/solr").build();The above is from solr Official website .
One 、 Build and run SolrJ Applications
For using Maven Projects built , pom.xml To configure :
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>7.3.1</version>
</dependency> If not maven Build the project , Only need to solr-solrj-7.3.1.jar and stay dist/solrj-lib Add the dependent packages in the directory to the project .
Two 、solr7 API
stay solr5 Tie back heel solr4 The biggest difference is that it is released as a separate application . No longer needed tomcat Equal container . In its internal integration jetty The server , He can pass bin The script of the directory runs directly to start .solr5 There are two modes of operation , Independent mode and cloud mode , Independent mode is based on core To manage , The cloud model is based on collection To manage .
SolrClient Is an abstract class , There are many implemented subclasses below ,
HttpSolrClient It is a general-purpose client . You can work with a Solr Nodes communicate directly .),
LBHttpSolrClient,CloudSolrClient,ConcurrentUpdateSolrClient
HttpSolrClient The creation of requires the user to specify one or more Solr Basics URL, Then the client uses Solr send out HTTP request .
- One URL The path of points to a specific core/collection( for example ,
http://host:8983/solr/core1) - One URL Point to the root Solr route ( for example ,
http://host:8983/solr). When not specified core/collection Base URL, You can request any core/collection, But the affected core/collection Must specify collection All requests for .
Generally speaking , If your SolrClient Will only be used in one core/collection, Including the path of entities is the most convenient .
3、 ... and 、 Create a project
Create a maven engineering ( ordinary java Projects are OK, but you need to guide the package yourself ), Add the dependency as follows :
establish Test class , test SolrJ relevant API1. add to \ Modify the index
/*
according to id( Unique constraint ) Domain to update Document The content of , If according to id Value search failed id The domain performs the add operation , If found, update .
*/
@Test
public void addDocument() throws IOException, SolrServerException {
/*
step
1、 establish HttpSolrClient object , Through it and Solr Server establishes connection .
2、 establish SolrInputDocument object , Then use it to add domains .
3、 adopt HttpSolrClient Object will SolrInputDocument Add to index library .
4、 Submit .
*/
final String solrUrl = "http://localhost:8983/solr/test_Core";
// establish solrClient Also specify the timeout , Do not specify the default configuration
HttpSolrClient solrServer = new HttpSolrClient.Builder(solrUrl)
.withConnectionTimeout(10000)
.withSocketTimeout(60000)
.build();
// 2、 establish SolrInputDocument object , Then use it to add domains .
SolrInputDocument document = new SolrInputDocument();
// The first parameter : The name of the domain , The name of the domain must be in schema.xml As defined in
// The second parameter : Domain value
// Be careful :id The domain of cannot be less
document.addField("id", "c0001");
document.addField("title_ik", " Use solrJ Added documents ");
document.addField("content_ik", " The content of the document ");
document.addField("product_name", " Name of commodity ");
// 3、 adopt HttpSolrServer Object will SolrInputDocument Add to index library .
solrServer.add(document);
// 4、 Submit .
solrServer.commit();
}Different solr edition solrj Is created in a different way
//solr4 How it was created
//SolrServer solrServer = new HttpSolrServer("http://127.0.0.1:8983/solr");
//solr5 How it was created , stay url It is specified in core name :core1
//HttpSolrClient solrServer=new HttpSolrClient("http://127.0.0.1:8983/solr/core1");
//solr7 How it was created , stay url It is specified in core name :core1
HttpSolrClient solrServer= new HttpSolrClient.Builder("http://127.0.0.1:8983/solr/core1").build();Query test
Delete index ( according to ID Delete )
// according to ID Delete index
@ Test
public void deleteDocument() throws IOException, SolrServerException {
final String solrUrl = "http://localhost:8983/solr/test_Core";
// establish solrClient Also specify the timeout , Do not specify the default configuration
HttpSolrClient solrServer = new HttpSolrClient.Builder(solrUrl)
.withConnectionTimeout(10000)
.withSocketTimeout(60000)
.build();
// according to ID Delete
solrServer.deleteById("c0001");
// Submit
solrServer.commit();
}Query test
Delete... According to conditions
// Delete... According to conditions
@Test
public void deleteDocumentByQuery() throws Exception {
final String solrUrl = "http://localhost:8983/solr/test_Core";
// establish solrClient Also specify the timeout , Do not specify the default configuration
// 1、 establish HttpSolrClient object , Through it and Solr Server establishes connection .
// Parameters :solrUrl Server's access address
HttpSolrClient solrServer = new HttpSolrClient.Builder(solrUrl)
.withConnectionTimeout(10000)
.withSocketTimeout(60000)
.build();
// according to ID Delete
solrServer.deleteByQuery("id:c0001");
// Delete all
// server.deleteByQuery("*:*");
// Submit
solrServer.commit();
}Simple query
/**
* Simple query
* @throws Exception
*/
@Test
public void queryIndex() throws Exception {
final String solrUrl = "http://localhost:8983/solr/test_Core";
// establish solrClient Also specify the timeout , Do not specify the default configuration
// 1、 establish HttpSolrClient object , Through it and Solr Server establishes connection .
// Parameters :solrUrl Server's access address
HttpSolrClient solrServer = new HttpSolrClient.Builder(solrUrl)
.withConnectionTimeout(10000)
.withSocketTimeout(60000)
.build();
// establish SolrQuery object
SolrQuery query = new SolrQuery();
// Set query conditions , name “q” Is fixed and must Of
query.set("q", "id:2");
// call server The query method of , Query index library
QueryResponse response = solrServer.query(query);
// Query results
SolrDocumentList results = response.getResults();
// The total number of query results
long cnt = results.getNumFound();
System.out.println(" The total number of query results :" + cnt);
for (SolrDocument solrDocument : results) {
System.out.println(solrDocument.get("id"));
System.out.println(solrDocument.get("product_name"));
System.out.println(solrDocument.get("product_sale_price"));
System.out.println(solrDocument.get("product_sort_name"));
System.out.println(solrDocument.get("product_pic"));
}
}Complex queries
Complex queries include highlighting
/**
* Complex queries Including highlighting
* @throws Exception
*/
@Test
public void queryIndex2() throws Exception {
final String solrUrl = "http://localhost:8983/solr/test_Core";
// establish solrClient Also specify the timeout , Do not specify the default configuration
// 1、 establish HttpSolrClient object , Through it and Solr Server establishes connection .
// Parameters :solrUrl Server's access address
HttpSolrClient solrServer = new HttpSolrClient.Builder(solrUrl)
.withConnectionTimeout(10000)
.withSocketTimeout(60000)
.build();
// establish SolrQuery object
SolrQuery query = new SolrQuery();
// Set query conditions
query.setQuery(" diamond ");
// Set filter conditions
query.setFilterQueries("product_sort_name: Humor groceries ");
// Set sort
query.setSort("product_sale_price",SolrQuery.ORDER.desc);
// Set paging information
query.setStart(0);
query.setRows(10);
// Set the list of fields that appear
query.setFields("id", "product_name", "product_sale_price",
"product_sort_name", "product_pic");
// Set the default search field
query.set("df", "product_name");
// Set highlight
query.setHighlight(true);
query.addHighlightField("product_name");
query.setHighlightSimplePre("<em>");
query.setHighlightSimplePost("</em>");
// call server The query method of , Query index library
QueryResponse response = solrServer.query(query);
// Query results
SolrDocumentList results = response.getResults();
// The total number of query results
long cnt = results.getNumFound();
System.out.println(" The total number of query results :" + cnt);
for (SolrDocument solrDocument : results) {
System.out.println(solrDocument.get("id"));
String productName = (String) solrDocument.get("product_name");
// Get the highlighted list
Map<String, Map<String, List<String>>> highlighting = response
.getHighlighting();
// Get the highlighted information of this document
List<String> list = highlighting.get(solrDocument.get("id")).get(
"product_name");
// If there is a highlight , Then assign the product name to the name with highlight
if (list != null) {
productName = list.get(0);
}
System.out.println(productName);
System.out.println(solrDocument.get("product_sale_price"));
System.out.println(solrDocument.get("product_sort_name"));
System.out.println(solrDocument.get("product_pic"));
}
}Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/111280.html Link to the original text :https://javaforall.cn
边栏推荐
- R language ggplot2 visual density map: Visual density map by group and custom configuration geom_ The alpha parameter in the density function sets the image transparency (to prevent multiple density c
- Guofu hydrogen energy rushes to the scientific and Technological Innovation Board: it plans to raise 2billion yuan, and 360million yuan of accounts receivable exceed the revenue
- MySQL user-defined function ID number to age (supports 15 / 18 digit ID card)
- 神经网络物联网未来发展趋势怎么样
- WebRTC的学习(二)
- SSH免密码登录详解
- TDengine 社区问题双周精选 | 第三期
- 区间 - 左闭右开
- 牛客网:拦截导弹
- TiCDC 6.0原理之Sorter演进
猜你喜欢

基于 TiDB 场景式技术架构过程 - 理论篇

Redis如何实现多可用区?

TiFlash 源码解读(四) | TiFlash DDL 模块设计及实现分析

LeetCode_2(两数相加)

如何将 DevSecOps 引入企业?

清大科越冲刺科创板:年营收2亿 拟募资7.5亿

tidb-dm报警DM_sync_process_exists_with_error排查

深拷贝真难

Financial one account Hong Kong listed: market value of 6.3 billion HK $Ye wangchun said to be Keeping true and true, long - term work

神经网络物联网未来发展趋势怎么样
随机推荐
R language ggplot2 visualization: visual line graph, using legend in theme function The position parameter defines the position of the legend
2022 machine fitter (Advanced) test question simulation test question bank simulation test platform operation
Lepton 无损压缩原理及性能分析
Make the seckill Carnival more leisurely: the database behind the promotion (Part 2)
Redis如何实现多可用区?
Request + BS4 crawl Netease cloud music popular comments
R语言ggplot2可视化:gganimate包基于transition_time函数创建动态散点图动画(gif)、使用shadow_mark函数为动画添加静态散点图作为动画背景
UE source code reading [1]--- starting with problems delayed rendering in UE
非技术部门,如何参与 DevOps?
展现强大。这样手机就不会难前进
After the microservice project is deployed, static resources and files uploaded to upload cannot be accessed. Solution
金融壹賬通香港上市:市值63億港元 葉望春稱守正篤實,久久為功
SAS接口有什么优势特点
In addition to the root directory, other routes of laravel + xampp are 404 solutions
Enjoy what you want. Zhichuang future
Tiflash compiler oriented automatic vectorization acceleration
国富氢能冲刺科创板:拟募资20亿 应收账款3.6亿超营收
神经网络物联网未来发展趋势怎么样
一网打尽异步神器CompletableFuture
Zhizhen new energy rushes to the scientific innovation board: the annual revenue is 220million, and SAIC venture capital is the shareholder