zoukankan      html  css  js  c++  java
  • Solr之java实现增删查操作

    1、添加pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.yangwj</groupId>
        <artifactId>demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <name>demo</name>
        <description>Demo project for Spring Boot</description>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.0.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
            <spring-cloud.version>Greenwich.M1</spring-cloud.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/org.apache.solr/solr-solrj -->
            <dependency>
                <groupId>org.apache.solr</groupId>
                <artifactId>solr-solrj</artifactId>
                <version>7.7.1</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpmime</artifactId>
                <version>4.5.7</version>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.5.6</version>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpcore</artifactId>
                <version>4.4.10</version>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/org.noggit/noggit -->
            <dependency>
                <groupId>org.noggit</groupId>
                <artifactId>noggit</artifactId>
                <version>0.8</version>
            </dependency>
    
            <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>1.4</version>
            </dependency>
            <dependency>
           <groupId>org.codehaus.woodstox</groupId>
                <artifactId>stax2-api</artifactId>
                <version>3.1.4</version>
            </dependency>
            <dependency>
                <groupId>org.codehaus.woodstox</groupId>
                <artifactId>woodstox-core-asl</artifactId>
                <version>4.4.1</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-simple</artifactId>
                <version>1.7.7</version>
            </dependency>
            <dependency>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
                <version>1.0.4</version>
            </dependency>
    
        </dependencies>
    
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-dependencies</artifactId>
                    <version>${spring-cloud.version}</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
        <repositories>
            <repository>
                <id>spring-milestones</id>
                <name>Spring Milestones</name>
                <url>https://repo.spring.io/milestone</url>
                <snapshots>
                    <enabled>false</enabled>
                </snapshots>
            </repository>
        </repositories>
    
    
    </project>

    2、创建Person.java类

    package com.yangwj.demo.Solr;
    
    import org.apache.solr.client.solrj.beans.Field;
    public class Person {
    
        @Field(value="id")
        private String id;
    
        @Field(value="name")
        private String name;
    
        @Field(value="description")
        private String description;
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getDescription() {
            return description;
        }
    
        public void setDescription(String description) {
            this.description = description;
        }
    
    }

    3、创建SolrUtil.java文件

    package com.yangwj.demo.Solr;
    
    import java.io.IOException;
    import java.util.List;
    
    import org.apache.solr.client.solrj.SolrQuery;
    import org.apache.solr.client.solrj.SolrServerException;
    import org.apache.solr.client.solrj.impl.HttpSolrClient;
    import org.apache.solr.client.solrj.impl.HttpSolrClient.Builder;
    import org.apache.solr.client.solrj.response.QueryResponse;
    import org.apache.solr.common.SolrDocument;
    import org.apache.solr.common.SolrDocumentList;
    import org.apache.solr.common.SolrInputDocument;
    
    
    public class SolrUtil {
        //指定solr服务器的地址
        private final static String SOLR_URL = "http://192.168.56.130:8983/solr/";
    
        /**
         * 创建SolrServer对象
         *
         * 该对象有两个可以使用,都是线程安全的
         * 1、CommonsHttpSolrServer:启动web服务器使用的,通过http请求的
         * 2、 EmbeddedSolrServer:内嵌式的,导入solr的jar包就可以使用了
         * 3、solr 4.0之后好像添加了不少东西,其中CommonsHttpSolrServer这个类改名为HttpSolrClient
         *
         * @return
         */
        public HttpSolrClient createSolrServer(){
            HttpSolrClient solr = null;
            solr = new HttpSolrClient.Builder(SOLR_URL).withConnectionTimeout(10000).withSocketTimeout(60000).build();
            return solr;
        }
    
    
        /**
         * 往索引库添加文档
         * @throws IOException
         * @throws SolrServerException
         */
        public void addDoc() throws SolrServerException, IOException{
            //构造一篇文档
            SolrInputDocument document = new SolrInputDocument();
            //往doc中添加字段,在客户端这边添加的字段必须在服务端中有过定义
            document.addField("id", "9");
            document.addField("name", "yangwenjie");
            document.addField("description", "a code man");
            //获得一个solr服务端的请求,去提交  ,选择具体的某一个solr core
            HttpSolrClient solr = new HttpSolrClient.Builder(SOLR_URL + "new_core").withConnectionTimeout(10000).withSocketTimeout(60000).build();
            solr.add(document);
            solr.commit();
            solr.close();
        }
    
    
        /**
         * 根据id从索引库删除文档
         */
        public void deleteDocumentById() throws Exception {
            //选择具体的某一个solr core
            HttpSolrClient server = new HttpSolrClient.Builder(SOLR_URL + "new_core").withConnectionTimeout(10000).withSocketTimeout(60000).build();
            //删除文档
            server.deleteById("8");
            //删除所有的索引
            //solr.deleteByQuery("*:*");
            //提交修改
            server.commit();
            server.close();
        }
    
        /**
         * 查询
         * @throws Exception
         */
        public void querySolr() throws Exception{
            HttpSolrClient solrServer = new HttpSolrClient.Builder(SOLR_URL + "new_core/").withConnectionTimeout(10000).withSocketTimeout(60000).build();
            SolrQuery query = new SolrQuery();
            //下面设置solr查询参数
            //query.set("q", "*:*");// 参数q  查询所有
            query.set("q","yangwenjie");//相关查询,比如某条数据某个字段含有周、星、驰三个字  将会查询出来 ,这个作用适用于联想查询
    
            //参数fq, 给query增加过滤查询条件
            query.addFilterQuery("id:[0 TO 9]");//id为0-4
    
            //给query增加布尔过滤条件
            //query.addFilterQuery("description:演员");  //description字段中含有“演员”两字的数据
    
            //参数df,给query设置默认搜索域
            query.set("df", "name");
    
            //参数sort,设置返回结果的排序规则
            query.setSort("id",SolrQuery.ORDER.desc);
    
            //设置分页参数
            query.setStart(0);
            query.setRows(10);//每一页多少值
    
            //参数hl,设置高亮
            query.setHighlight(true);
            //设置高亮的字段
            query.addHighlightField("name");
            //设置高亮的样式
            query.setHighlightSimplePre("<font color='red'>");
            query.setHighlightSimplePost("</font>");
    
            //获取查询结果
            QueryResponse response = solrServer.query(query);
            //两种结果获取:得到文档集合或者实体对象
    
            //查询得到文档的集合
            SolrDocumentList solrDocumentList = response.getResults();
            System.out.println("通过文档集合获取查询的结果");
            System.out.println("查询结果的总数量:" + solrDocumentList.getNumFound());
            //遍历列表
            for (SolrDocument doc : solrDocumentList) {
                System.out.println("id:"+doc.get("id")+"   name:"+doc.get("name")+"    description:"+doc.get("description"));
            }
    
            //得到实体对象
            List<Person> tmpLists = response.getBeans(Person.class);
            if(tmpLists!=null && tmpLists.size()>0){
                System.out.println("通过文档集合获取查询的结果");
                for(Person per:tmpLists){
                    System.out.println("id:"+per.getId()+"   name:"+per.getName()+"    description:"+per.getDescription());
                }
            }
        }
    
        public static void main(String[] args) throws Exception {
            SolrUtil solr = new SolrUtil();
            //solr.createSolrServer();
            //solr.addDoc();
            //solr.deleteDocumentById();
            solr.querySolr();
        }
    }

    4、如果出现错误,一般是pom.xml中的jar包太低,因此需要更高版本的包。

  • 相关阅读:
    使用OwnCloud建立属于自己私有的云存储网盘
    Linux服务器学习----tomcat 服务配置实验报告(一)
    Linux服务器学习----haproxy+keepalived
    Docker容器版Jumpserver堡垒机搭建部署方法附Redis
    Dokcer的一些命令:
    Docker安装prometheus监控
    CentOS7安装Docker
    用Dockerfile来制作contos镜像
    CentOS7中服务器网卡配置——配置静态IP
    CentOS7中搭建rabbitmq单机
  • 原文地址:https://www.cnblogs.com/ywjfx/p/10485430.html
Copyright © 2011-2022 走看看