当前位置:网站首页>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 API
1. 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
边栏推荐
- Some ideas about Apache mesos
- Getting started with rce
- Mingfeng medical sprint technology innovation board: annual revenue of 350million yuan, proposed to raise 624million yuan
- PHP5下WSDL,SOAP调用实现过程
- MySQL user-defined function ID number to age (supports 15 / 18 digit ID card)
- R language uses boxplot function in native package (basic import package, graphics) to visualize box plot
- Leetcode array question brushing notes
- 魅族新任董事长沈子瑜:创始人黄章先生将作为魅族科技产品战略顾问
- POI set the data format of the column (valid)
- 治臻新能源冲刺科创板:年营收2.2亿 上汽创投是股东
猜你喜欢
[machine learning notes] several methods of splitting data into training sets and test sets
如何将 DevSecOps 引入企业?
Comparison of several distributed databases
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
UE source code reading [1]--- starting with problems delayed rendering in UE
牛客网:拦截导弹
金融壹账通香港上市:市值63亿港元 叶望春称守正笃实,久久为功
Kunlun Taike rushes to the scientific innovation board: the annual revenue is 130million, and it plans to raise 500million. CETC Taiji holds 40% of the shares
[js] basic syntax - for loop
LeetCode_2(两数相加)
随机推荐
Judge whether the variable is an array
LeetCode_3(无重复字符的最长子串)
What is the future development trend of neural network Internet of things
The simplest way to open more functions without certificates
基于 TiDB 场景式技术架构过程 - 理论篇
强联通分量
金融壹账通香港上市:市值63亿港元 叶望春称守正笃实,久久为功
微服务项目部署后,无法访问静态资源,无法访问到上传到upload中的文件,解决办法
LeetCode_69(x 的平方根 )
WebRTC的学习(二)
Enjoy what you want. Zhichuang future
根据CronSequenceGenerator计算cron表达式的时间
锚点导航小demo
Make the seckill Carnival more leisurely: the database behind the promotion (Part 2)
软件测试人在深圳有哪些值得去的互联网公司【软件测试人员专供版】
Simple process of penetration test
常见问题之PHP——Fatal error: Allowed memory size of 314572800 bytes exhausted...
[buuctf.reverse] 152-154
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
Google EventBus 使用详解