Solr 8.2 User Guide

1 Solr Introduction

What is 1.1 Solr

Solr is an enterprise-class application server-based full-text search. You can enter a text, by word retrieve data. It is a separate service, deployed in tomcat.

Why do we need Solr 1.2

Question: We have learned Lucene, why should learn solr?

Lucene is a kit, alone can not run, the need to import java code. Solr can run independently in the tomcat container, through the http protocol, by way of an interface to provide services, java code only need to focus on the business process can be.

image

1.3 Solr directory structure

image

  • bin: solr running script
  • contrib: solr some extensions jar package, used to enhance the function of solr
  • dist: This directory contains jar file generated during the build, and the associated dependencies
  • example: solr directory project examples
  • licenses: solr some relevant licensing information

2 start example

2.1 Requirements

The data in the database import solr, the realization of inquiry

2.2 Configuration Steps

2.2.1 Start solr

Go to the bin directory under solr extraction path, press shift + right mouse button and select the Open command-line tool

image

Enter the command: .\solr startstart solr service

image

Use a browser to access localhost: 8983 to enter the backstage control page.

image

2.2.2 Configuration solr core

Continue to create a core command tool, core project is equivalent to an example of a solr.

command:solr create -c <core_name>

image

After successfully created, you can solr-8.2.0/server/solr/<core_name>see the automatically generated default configuration file directory

image

Once created, re-enter the backstage control page, you can find the newly created core

image

2.2.3 Creating java program to access the server solr

Step Description:

  1. Data collection
  2. Convert the data into Solr documents
  3. Solr server connection, write documents to index database

2.2.3.1 create a project, import the jar package

Need to import the package are:

  • Solrj core package:solr-8.2.0\dist\solr-core-8.2.0.jar
  • Solrj dependencies: solr-8.2.0\dist\solrj-lib\all the packages directory
  • JDBC 驱动包:根据数据库版本而定,我这里拷的是 mysql 8 的驱动包

项目结构:

image

2.2.3.2 采集数据

需求采集的字段说明:

  • 参与搜索的字段:名称、价格、商品类别、描述信息
  • 参与结果展示的字段:商品id、图片
(1)创建 pojo
public class Product {
    private Integer pid;
    private String name;
    private String categoryName;
    private Double price;
    private String description;
    private String picture;
    //省略 getter、setter、constructor、toString
}
(2)创建 dao
public class ProductDao {

    public List<Product> listAll() {
        List<Product> products = new ArrayList<>();
        //获取数据库连接
        Connection conn = JdbcUtils.getConnection();

        String sql = "select * from `products`";
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            //创建 statement
            statement = conn.createStatement();
            //执行 sql 语句
            resultSet = statement.executeQuery(sql);
            //循环操作结果集
            while (resultSet.next()) {
                products.add(new Product(resultSet.getInt("pid"),
                        resultSet.getString("name"),
                        resultSet.getString("category_name"),
                        resultSet.getDouble("price"),
                        resultSet.getString("description"),
                        resultSet.getString("picture")));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if (null != resultSet) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                } finally {
                    if (null != statement) {
                        try {
                            statement.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        } finally {
                            if (null != conn) {
                                try {
                                    conn.close();
                                } catch (SQLException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
        }

        return products;
    }
}
(3)将数据转换成 solr 文档, SolrInputDocument 对象

Solr是通过一个配置文件managed-schema,事先定义域的信息的,需要先定义再使用。

image

配置文件里面事先定义好了各种 <dynamicField>,能够根据命名动态的指定域的类型,也就是 type 属性。

image

而域的类型也在此做了定义,用的是 <fieldType> 标签。(可对比 lucene 理解)

image

其中,text-general 指定了分词器,以及一些拓展配置文件

image

我们可以根据需要,按照上述例子,手动的声明几个域,并使用中文分词。先将 lucene 中的 SmartChineseAnalyzer 的 jar 包拷入文件夹中

image

再修改 managed-schema 配置文件,添加以下内容

image

重启服务器后,可以看到效果

image

为 dao 添加 getDocuments 方法

public List<SolrInputDocument> getDocuments(List<Product> products) {
    List<SolrInputDocument> documents = new ArrayList<>();
    products.forEach(product -> {
        SolrInputDocument document = new SolrInputDocument();
        document.addField("id", product.getPid());//对应solr的uniqueKey
        document.addField("product_name", product.getName());
        document.addField("product_price", product.getPrice());
        document.addField("product_category_name", product.getCategoryName());
        document.addField("product_picture", product.getPicture());
        document.addField("product_description", product.getDescription());
        documents.add(document);
    });

    return  documents;
}

创建索引库

@Test
public void createIndex() {
    //1.创建 HttpSolrClient.Builder 对象,通过它创建客户端通信
    HttpSolrClient.Builder builder = new HttpSolrClient.Builder("http://localhost:8983/solr");
    HttpSolrClient solrClient = builder.build();

    //2.通过 client 将 document 加入索引库
    ProductDao dao = new ProductDao();
    try {
        //参数1是 solr core 的名字
        solrClient.add("product", dao.getDocuments(dao.listAll()));
        solrClient.commit("product");
        System.out.println("创建索引库完成");
    } catch (SolrServerException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

导入成功后可以在后天控制页面看到结果

image

2.2.3.3 搜索索引

@Test
public void queryTest() {
    //1.创建 HttpSolrClient.Builder 对象,通过它创建客户端通信
    HttpSolrClient.Builder builder = new HttpSolrClient.Builder("http://localhost:8983/solr");
    HttpSolrClient solrClient = builder.build();
    //2.创建一个map封装搜索条件
    Map<String, String> queryMap = new HashMap<>();
    queryMap.put("q","音乐盒");//关键字
    queryMap.put("df", "product_name");//默认搜索域
    //queryMap.put("sort","id asc");//结果以 id 升序排列,默认以关联度排序
    queryMap.put("rows","20");//默认只有十条
    //3.使用map创建 MapSolrParams 对象
    SolrParams solrParams = new MapSolrParams(queryMap);
    try {
        //4.使用客户端进行查询
        QueryResponse response = solrClient.query("product", solrParams);
        //5.提取结果
        SolrDocumentList documents = response.getResults();

        System.out.println("一共查询到:" + documents.getNumFound() + "条结果");

        //6.循环输出
        documents.forEach(document ->{
            System.out.println("编号" + document.get("id") + ":" + document.get("product_name"));
        });
    } catch (SolrServerException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

3 solr管理控制台

3.1 查询界面说明

image

可以根据查询界面各个关键字,设置上述代码 queryMap,实现复杂的查询功能。key 对应的就是关键字,value 就是输入框内的值。

3.2 安装DataImport插件

3.2.1 Dataimport插件说明

使用该插件后,可以在管理界面直接从数据库导入数据到索引库。(即:一个插件解决入门示例中,创建索引的全部操作)

3.2.2 安装步骤

(1)拷贝相关 jar 包到文件夹

image

(2)修改 \solr-8.2.0\server\solr\product\conf\solrconfig.xml 文件,增加以下代码

image

(3) in \solr-8.2.0\server\solr\product\conf\New DIHconfig.xml file directory, and write the following

<dataConfig>
    <dataSource type="JdbcDataSource"
                driver="com.mysql.cj.jdbc.Driver"
                url="jdbc:mysql://localhost:3306/solr?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false"
                user="root"
                password="password"
    />
    <document>
        <entity name="product"
                query="SELECT * FROM products">
            <field column="pid" name="id"/>
            <field column="name" name="product_name"/>
            <field column="price" name="product_price"/>
            <field column="category_name" name="product_category_name"/>
            <field column="description" name="product_description"/>
            <field column="picture" name="product_picture"/>
        </entity>
    </document>
</dataConfig>

(4) Restart solr service

image

3.2.3 Testing

(1) Clear index Library

image

(2) introduced into the index database

image

Guess you like

Origin www.cnblogs.com/carlosouyang/p/11352779.html