SOLR를 사용하여 데이터 조작에 대한 코드

I. 서론

작동 SOLR 모드 세 가지가 있습니다 :

1, Solrj 작업을 사용하여 JavaSE 프로그램 개발 .

2 스프링 SOLR 데이터를 사용하여 동작하는 프로그램 개발에 대한 SSM .

3, springboot 플러그 springboot-스타터 SOLR 데이터를 사용하여 동작 springboot 프로그램 개발 .

둘째, Solrj를 사용하여 코드를 개발

1, 메이븐의 도입을 지원

<의존성> 
    <의 groupId> org.apache.solr </의 groupId> 
    <artifactId를> SOLR-solrj </ artifactId를> 
    <version>은 8.2.0 </ 버전> 
</ 의존성>

2, SOLR의 CRUD 코드의 준비를 위해. 다음 예는 다음과 같다 :

수입 org.apache.solr.client.solrj.SolrQuery;
수입 org.apache.solr.client.solrj.SolrServerException;
수입 org.apache.solr.client.solrj.impl.HttpSolrClient;
수입 org.apache.solr.client.solrj.response.QueryResponse;
수입 org.apache.solr.common.SolrDocument;
수입 org.apache.solr.common.SolrDocumentList;
수입 org.apache.solr.common.SolrInputDocument; 

수입 때 java.io.IOException; 

/ ** 
 * 2019년 9월 6일에 데이비드 작성. 
 * / 
공용  클래스 TestSolr { 

    개인  정적  최종 문자열 solrUrl = "HTTP : // localhost를 : 8983 / SOLR / 기사"; 

    // 정보 및 변경 정보를 추가 
    공개  무효 ) (addSolr를 던졌습니다 SolrServerException, IOException가 { 
        HttpSolrClient solrClient = 새로운 새로운 HttpSolrClient.Builder (solrUrl) 
                .withConnectionTimeout ( 10000 ) 
                .withSocketTimeout ( 60000 ) 
                .build (); 
        SolrInputDocument 문서 = 새로운 새로운 SolrInputDocument () ;
         // 참고 : id 필드 이하 수 
        document.addField ( "ID", "10" ); 
        document.addField ( "제목", "자바 기반의 객체 지향 프로그래밍" );
        solrClient.add (문서) 
        solrClient.commit (); 
    } 

    // 정보를 삭제 
    공공  무효 (delSolr)가 발생 IOException이, SolrServerException { 
        HttpSolrClient solrClient = 새로운 새로운 HttpSolrClient.Builder (solrUrl) 
                .withConnectionTimeout ( 10000 ) 
                .withSocketTimeout ( 60000 ) 
                .build를 (); 
        solrClient.deleteById ( "10"); // 삭제 
        solrClient.commit을 (); // 제출 
    } 

    // 쿼리 정보 
    공개  무효 searchSolr는 () 가 발생합니다 IOException이, SolrServerException { 
        HttpSolrClient solrClient = 새로운 새 HttpSolrClient.Builder (solrUrl) 
                .withConnectionTimeout ( 10000 ) 
                .withSocketTimeout ( 60000 ) 
                ; .build () 
        SolrQuery 쿼리 = 새로운 새 SolrQuery을 (); 
        query.set를 ( "Q", " 이름 : 프로그램 " );
         // 호출 쿼리 방법 서버, 쿼리 색인 데이터베이스 
        QueryResponse 응답 = solrClient.query (쿼리);
         // 쿼리 결과 
        SolrDocumentList 결과 = response.getResults ();
         // 결과 조회 총수
         CNT = results.getNumFound (); 
        에서 System.out.println ( "查询结果总数:"+ CNT);
        (SolrDocument solrDocument : 결과) { 
            에서 System.out.println (solrDocument.get ( "ID" )); 
            에서 System.out.println (solrDocument.get ( "제목" )); 
        } 
    } 
}

三、使用spring-data-solr开发代码

하나는 소개 Maven은 일치 최신 버전 4.0 문서하지 않는 스프링 데이터 SOLR 작동 코드의 다른 버전을 지원합니다.

참고 : 해당 버전 5.1.9의 봄 버전 4.0, 동일한 버전 springMVC 그렇지 않으면 오류가보고 될 수 있습니다.

<의존성> 
    <의 groupId> org.springframework.data </의 groupId> 
    <artifactId를> 스프링 데이터 SOLR </ artifactId를> 
    <version>은 4.0.10.RELEASE </ 버전> 
</ 의존성>

 

인덱스 필드 @ @Id 기본 키 식별자, SOLR 항목 식별자에 충전되는 것을 특징으로하는 2 POJO를 준비. 초기 사용 스프링 데이터 solrs 및 주석 solrj에 있습니다 @Field

@SolrDocument (solrCoreName = "기사" )
 공공  클래스 기사 구현 직렬화 { 
    @Id 
    @Indexed 
    개인  INT의 ID를; 
    @Indexed 
    개인 문자열 제목;
    개인 문자열 내용; 
    @Indexed 
    개인 날짜 createDate을; 
}

 

3, 봄 프로파일 스프링 solr.xml의 준비, 노트 HTTP 참조 만 주소 : // localhost를 : 8983 / SOLR,이 프로젝트는 여러 컬렉션이 필요할 수 있기 때문이다.

<? XML 버전 = "1.0"인코딩 = "UTF-8"?> 
<콩의 xmlns = "http://www.springframework.org/schema/beans" 
       의 xmlns :이 xsi = "http://www.w3.org / 2001 / 된 XMLSchema 인스턴스 " 
       XSI :의 schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd을 "> 
    <! - SOLR服务器地址-> 
    <콩 ID = "solrClientFactory" 클래스 = "org.springframework.data.solr.server.support.HttpSolrClientFactoryBean"> 
        <속성 이름 = "URL"값 = " HTTP : // localhost를 : 8983 / SOLR "/> 
        <속성 명 ="타임 아웃 "값 ="5000 "/>
        <속성 명 = "의 MaxConnections 「값 ="100 "/> 
    </ 빈>  
    <! - SOLR模板->
    <빈 ID ="solrTemplate "클래스 = "org.springframework.data.solr.core.SolrTemplate"> 
        <생성자, 인수 지수 = "0"REF = "solrClientFactory"/> 
    </ 빈> 
</ 콩>

 

4, 컨트롤러 코드주의가 작업 컬렉션을 지정해야합니다.

수입 org.apache.solr.client.solrj.response.UpdateResponse;
수입 org.lanqiao.entity.Articles;
수입 org.springframework.beans.factory.annotation.Autowired;
수입 org.springframework.data.domain.Sort;
수입 org.springframework.data.solr.core.SolrTemplate;
수입 org.springframework.data.solr.core.query.Criteria;
수입 org.springframework.data.solr.core.query.Query;
수입 org.springframework.data.solr.core.query.SimpleQuery;
수입 org.springframework.data.solr.core.query.result.ScoredPage;
수입 org.springframework.stereotype.Controller;
수입org.springframework.web.bind.annotation.RequestMapping;
수입 org.springframework.web.bind.annotation.ResponseBody; 

수입 java.util.Date;
수입 은 java.util.List;
수입 java.util.Optional; 


/ ** 
 * 2019년 9월 7일에 데이비드 작성. 
 * / 
@Controller 
공공  클래스 ArticlesController { 
    @Autowired 
    개인 SolrTemplate solrTemplate; 

    (@RequestMapping "/ 저장" ) 
    @ResponseBody 
    공공 ) 문자열 keywordsSearchSpring을 ({ 
        기사 기사 = 새로운  ) (기사;
        articles.setId ( 11 ); 
        articles.setTitle ( "山东济南商城" ); 
        articles.setCreateDate ( 새로운 날짜 ()); 
        solrTemplate.saveBean ( "기사" , 기사) 
        solrTemplate.commit ( "제품" );
        반환 "성공은 저장!" ; 
    } 

    @RequestMapping ( "/ GET" ) 
    @ResponseBody 
    공공 selectById () {기사 
        옵션 (기사, "기사"1. <기사> 옵션 = solrTemplate.getById 클래스 );
        복귀 ) (optional.get; 선택 jdk1.
    } 

    @RequestMapping ( "/ 삭제" ) 
    @ResponseBody 
    공개  INT delById () { 
        UpdateResponse updateResponse = solrTemplate.deleteByIds ( "문서", "11" );
        복귀 ) (updateResponse.getStatus 단계; // 0表示成功
    } 

    @RequestMapping ( "/ 선택" ) 
    @ResponseBody 
    공개 목록 <기사> 를 선택 () {
         // 查询所有 
        검색어 쿼리 = SimpleQuery (); 
        
        // 设置条件 
        기준 기준 = 새로운 기준 ( "제목"). "(인 
        query.addCriteria (기준); 
        
        // 설정 페이지 
        query.setOffset (0L이); // 인덱스 (기본값 0)를 시작 
        query.setRows을 (2);   // 각 기록의 페이지 번호 (기본값 10) 

        // 데이터 정렬을 설정 
        정렬 정렬 = 새로운 새로운 정렬 (Sort.Direction.ASC, "createDate을" ); 
        query.addSort (정렬); 
        
        // 쿼리 
        ScoredPage <기사> 페이지 = solrTemplate.queryForPage ( " 기사 ", 쿼리, 기사. 클래스 ) 
        에서 System.out.println ( "pages.getTotalElements () = "+ pages.getTotalElements ()); 
        목록 <기사>내용 = pages.getContent ();
         반환 내용; 
    }
    
}

 

지식은 다음과 같이 프로그램 목록의 여기 SpringMVC 부분이 자세히 설명되지 않은 :

 

세, 개발에 플러그인을 springboot

springboot 플러그인 기본값은 사용하는 것입니다 solrjSolrClient 객체 구현 SOLR 작업을. : 블로그를 참조 https://www.jianshu.com/p/05a161add1a6을

개인적으로 나는 생각 스프링 데이터 SOLRSolrTemplate가 개발에 더 적합, 그래서 여기에 초점이 기본 solrj 스프링 데이터를-SOLR 변경하는 방법에 대해 이야기한다.  

1, 메이븐의 도입을 지원

<의존성> 
    <의 groupId> org.springframework.boot </의 groupId> 
    <artifactId를> 스프링 부팅 스타터 데이터 SOLR </ artifactId를> 
</ 의존성>

 

즉 지원 Solrj의 도입도 스프링 데이터 SOLR SOLR 지원 작업을 구현 것을 알 수있다.

도 2를 참조하면, 루트 만 경로를 배치 스프링 SOLR 데이터를 이용하여 구성 파일있는 application.properties.

# SOLR配置
spring.data.solr.host = HTTP : // localhost를 : 8983 / SOLR

 

 

도 3은, 설정 파일의 제조 방법은, 패키지가 SolrClinet SolrTemplate의 스프링 - 데이터 - SOLR Solrj이다.

import org.apache.solr.client.solrj.SolrClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.solr.core.SolrTemplate;

@Configuration
public class MySolrConfig {
    @Autowired
    SolrClient solrClient;

    @Bean
    public SolrTemplate getSolrTemplate() {
        return new SolrTemplate(solrClient);
    }

}

 

这样就可以使用SolrTemplate对象来操作Solr了,controller中的操作方法和entity中的对象都不用改变,同上面的代码。

程序清单:

 

POJO代码:

controller代码:

 

 

参考文章:

https://blog.csdn.net/likemebee/article/details/78469002

https://www.jianshu.com/p/05a161add1a6

https://blog.csdn.net/zhuzg2005/article/details/89598925

 

 

추천

출처www.cnblogs.com/david1216/p/11482228.html