With the development of the Internet and the explosive growth of information, the amount of information we can now access and obtain is very large. Whether it is information obtained from web pages, literature or daily life, we need an efficient way to process and manage. Full-text search is a very efficient and commonly used way to locate and extract the information we need through keywords or phrases, and Solr is a tool that is very suitable for full-text search development.
This article will introduce the basic concepts of Solr and how to use Solr for full-text search in Java API development.
1. Introduction to Solr
Solr is essentially an open source enterprise search platform, which is based on the Apache Lucene Java library and provides some convenient REST APIs. According to Solr’s official introduction, it mainly includes the following features:
- Full-text search
- Real-time search
- Website search
- Distributed search
- Database integration
- Parsing of multiple file formats
- Export of multiple file formats
- External configuration
As a An enterprise-level search platform, Solr provides very complete search functions and flexible configuration methods, which makes it easy for us to develop search modules in actual development. Below we will focus on how to use Solr for full-text search in Java API development.
2. Use Solr for full-text search
2.1 Install Solr
First, we need to install Solr in the local environment or server. Solr officially provides a very convenient way to install and run Solr:
- Download Solr address: https://lucene.apache.org/solr/downloads.html.
- Unzip the file: tar -zxvf solr-x.x.x.zip.
- Enter the decompressed folder: cd solr-x.x.x.
- Start Solr: bin/solr start.
2.2 Create Solr Core and define Schema
Solr Core is a very core concept in Solr. It is equivalent to an independent search environment, including data index and search request deal with. In Solr, we can create multiple Cores, and each Core can have independent configuration and data sets.
In Solr, we need to first create a Core and then define the Schema for search. Schema defines data fields, types, indexes and other attributes, which will affect the efficiency and accuracy of search.
You can use Solr's own Schema or user-defined Schema to define the field attributes required for search. Here we introduce the use of Solr's default Schema.
Use Solr's own default Schema:
-
Create core:
bin/solr create_core -c <core name>
-
Clear all created fields:
curl http://localhost:8983/solr/<core name>/schema -H 'Content-type:application/json' -d '{"delete-all-fields":{}}'
-
Add fields:
curl http://localhost:8983/solr/<core name>/schema -H 'Content-type:application/json' -d ' { "add-field":{ "name":"field_name", "type":"string", "stored":true } }'
- Restart Solr service
Use user-defined Schema:
Users can Customize Schema to meet different application needs. Solr provides Schema API. Provides easy Schema addition for creators.
-
Create core:
bin/solr create_core -c <core name>
-
Add field:
- Add field type:
Add field to Solr server Send a POST request with content_type set to application/json
{ "add-field-type": { "name":"test_fieldType","class":"solr.TextField","indexAnalyzer":{ "tokenizer":{ "class":"solr.StandardTokenizerFactory" },"filters":[ { "class":"solr.StopFilterFactory", "ignoreCase":true, "words":"stopword.txt", "format":"snowball", "enablePositionIncrements":true },{ "class":"solr.SnowballPorterFilterFactory", "language":"English" } ], "queryAnalyzer":{ "tokenizer":{ "class":"solr.StandardTokenizerFactory" },"filters":[ { "class":"solr.StopFilterFactory", "ignoreCase":true, "words":"stopword.txt", "format":"snowball", "enablePositionIncrements":true },{ "class":"solr.SnowballPorterFilterFactory", "language":"English" } ] } } }
- Add field (title): A response will be returned after the
{ "add-field": { "name": "title", "type": "text_en", "stored": true } }
field is added successfully.
- Add field type:
-
Specify this Schema in Solr config:
Enter the ${core}/conf directory to modify solrconfig.xml and add the following code:
<schemaFactory class="ClassicIndexSchemaFactory"/> <schema name="schema_name" version="1.5"> <field name="title" type="text_en" indexed="true" stored="true" /> </schema>
2. Use Solr in Java API for full-text search
Next, we will introduce how to use Solr's Java API for full-text search in Java Web applications.
- Add SolrJ dependency
In the Maven project, we need to add SolrJ dependency. Solr officially provides a very convenient dependency:
<dependency> <groupId>org.apache.solr</groupId> <artifactId>solr-solrj</artifactId> <version>8.2.0</version> </dependency>
- Use SolrJ to search in code
In Java code, we can use QueryResponse and SolrClient provided by SolrJ to perform search operations. The queried data can be viewed as key-value pairs.
First, we need to create an instance of SolrClient. In SolrJ, SolrClient is the client of Solr and provides a method to directly call the Solr REST API.
String solrUrl = "http://localhost:8983/solr/core_name"; SolrClient solr = new HttpSolrClient.Builder(solrUrl).build();
Then, we need to create a SolrQuery object, which is used to set search parameters, including search keywords, sorting rules, filter conditions, etc.
SolrQuery query = new SolrQuery(); query.setQuery("keyword"); query.setStart(0); query.setRows(10); query.setSort("sort_field", SolrQuery.ORDER.asc); query.addFilterQuery("filter_field:filter_value");
Finally, we can perform a search through the solr.query(query) method, and the returned QueryResponse contains the search results and related metadata information. We need to get the search results list through the response.getResults() method.
QueryResponse response = solr.query(query); SolrDocumentList results = response.getResults();
In actual development, we can also perform secondary processing on the search results as needed, such as converting the results into JSON format or Java objects.
for (SolrDocument result : results) { String id = (String) result.getFieldValue("id"); String title = (String) result.getFieldValue("title"); String content = (String) result.getFieldValue("content"); // 将搜索结果转换为 Java 实体类 SearchResult item = new SearchResult(id, title, content); // 或将搜索结果转换为 JSON 字符串 String json = new ObjectMapper().writeValueAsString(result); }
The above is the basic process of using Solr for full-text search in Java API development. Solr provides very complete search functions and Java API support, allowing us to easily develop efficient and accurate search modules to provide users with a better search experience.
The above is the detailed content of Using Solr for full-text search in Java API development. For more information, please follow other related articles on the PHP Chinese website!

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
