search
HomeJavajavaTutorialUsing Solr for full-text search in Java API development

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:

  1. Create core:

    bin/solr create_core -c <core name>
  2. Clear all created fields:

    curl http://localhost:8983/solr/<core name>/schema -H 'Content-type:application/json' -d '{"delete-all-fields":{}}'
  3. 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
        }
     }'
  4. 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.

  1. Create core:

    bin/solr create_core -c <core name>
  2. 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.

  3. 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.

  1. 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>
  1. 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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does the class loader subsystem in the JVM contribute to platform independence?How does the class loader subsystem in the JVM contribute to platform independence?Apr 23, 2025 am 12:14 AM

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

Does the Java compiler produce platform-specific code? Explain.Does the Java compiler produce platform-specific code? Explain.Apr 23, 2025 am 12:09 AM

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

How does the JVM handle multithreading on different operating systems?How does the JVM handle multithreading on different operating systems?Apr 23, 2025 am 12:07 AM

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

What does 'platform independence' mean in the context of Java?What does 'platform independence' mean in the context of Java?Apr 23, 2025 am 12:05 AM

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

Can Java applications still encounter platform-specific bugs or issues?Can Java applications still encounter platform-specific bugs or issues?Apr 23, 2025 am 12:03 AM

Javaapplicationscanindeedencounterplatform-specificissuesdespitetheJVM'sabstraction.Reasonsinclude:1)Nativecodeandlibraries,2)Operatingsystemdifferences,3)JVMimplementationvariations,and4)Hardwaredependencies.Tomitigatethese,developersshould:1)Conduc

How does cloud computing impact the importance of Java's platform independence?How does cloud computing impact the importance of Java's platform independence?Apr 22, 2025 pm 07:05 PM

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

What role has Java's platform independence played in its widespread adoption?What role has Java's platform independence played in its widespread adoption?Apr 22, 2025 pm 06:53 PM

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

How do containerization technologies (like Docker) affect the importance of Java's platform independence?How do containerization technologies (like Docker) affect the importance of Java's platform independence?Apr 22, 2025 pm 06:49 PM

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version