将Solarium与SOLR结合使用进行搜索-Solarium和GUI

This is the second article in a four part series on using Solarium, in conjunction with Apache’s SOLR search implementation.

这是与Solarium结合使用的四部分系列的第二篇文章,结合Apache的SOLR搜索实现。

In the first part, I introduced the key concepts and we installed and set up SOLR. In this second part we’ll install Solarium, start building an example application, populate the search index and get into a position where we can start running searches.

第一部分中 ,我介绍了关键概念,然后我们安装并设置了SOLR。 在第二部分中,我们将安装Solarium,开始构建示例应用程序,填充搜索索引,然后进入可以开始运行搜索的位置。

创建应用程序 (Creating the Application)

Create a new Laravel application via Composer:

通过Composer创建一个新的Laravel应用程序:

composer create-project laravel/laravel movie-search --prefer-dist

Make the storage directory app/storage directory writeable.

使存储目录app/storage目录可写。

安装日光浴室 (Installing Solarium)

You’ll recall from the first part that the Solarium Project provides a level of abstraction over the underlying SOLR requests which enables you to code as if SOLR were a native search implementation running locally, rather than worry about issuing HTTP requests or parsing the responses.

您会从第一部分中回想起, Solarium项目提供了对基础SOLR请求的抽象级别,使您可以像SOLR是在本地运行的本机搜索实现那样进行编码,而不必担心发出HTTP请求或解析响应。

By far the best way to install Solarium is using Composer:

到目前为止,安装Solarium的最佳方法是使用Composer:

"solarium/solarium": "dev-develop"

Alternatively you can download or clone it from Github.

或者,您可以从Github下载或克隆它。

If you’re following along and building the movie search application, this will go in your newly created project’s composer.json file just as you would any other third-party package; there’s no Laravel service provider though, in this case.

如果您正在继续并构建电影搜索应用程序,则它将像其他任何第三方软件包一样放入新创建的项目的composer.json文件中。 在这种情况下,虽然没有Laravel服务提供商。

配置日光浴室 (Configuring Solarium)

The constructor to the Solarium client takes an array of connection details, so create a configuration file – app/config/solr.php as follows:

Solarium客户端的构造函数采用了一系列连接详细信息,因此, app/config/solr.php按如下所示创建配置文件– app/config/solr.php

return array(
    'host'      => '127.0.0.1',
    'port'      => 8983,
    'path'      => '/solr/',
):

If you’ve installed SOLR as per the instructions in the first part these defaults should be just fine, although in some circumstances you may need to change the port number.

如果按照第一部分中的说明安装了SOLR,则这些默认值应该很好,尽管在某些情况下,您可能需要更改端口号。

For simplicity, we’re simply going to create an instance of the Solarium client as a property of the controller (app/controllers/HomeController.php):

为简单起见,我们仅创建一个Solarium客户端实例作为控制器的属性( app/controllers/HomeController.php ):

/**
     * @var The SOLR client.
     */
    protected $client;

    /**
     * Constructor
     **/
    public function __construct()
    {
        // create a client instance      
        $this->client = new \Solarium\Client(Config::get('solr'));
    }

Normally in Laravel you’d create an instance in a service provider bound to the IoC container, but this way will do fine for what’s a pretty simple application.

通常,在Laravel中,您将在绑定到IoC容器的服务提供程序中创建一个实例,但是这种方式对于一个非常简单的应用程序来说会很好。

平查询 (Ping Queries)

A ping query is useful for checking that the SOLR server is running and accessible, and therefore a good place to begin. Using Solarium it’s simple, so you may wish to test if everything is working by using the following:

ping查询对于检查SOLR服务器是否正在运行且可访问是有用的,因此是一个不错的起点。 使用Solarium很简单,因此您可能希望使用以下方法测试一切是否正常:

// create a ping query
$ping = $client->createPing();

// execute the ping query
try {
    $result = $client->ping($ping);
} catch (Solarium\Exception $e) {
    // the SOLR server is inaccessible, do something
}

As the example illustrates, an inaccessible SOLR instance throws an exception, so you can act accordingly by catching it at this point.

如示例所示,无法访问的SOLR实例引发异常,因此您可以通过在此时捕获它来采取相应的行动。

样本数据 (Sample Data)

For the purposes of this tutorial we’re going to build a simple movie search. I’ve created a CSV file containing around 2,000 movies around a bunch of keywords (for example space, night and house) which you can download, or if you want to create your own, you might want to check out the Rotten Tomatoes API. (As an aside, but one which is related, IMDB make their data available but spread over a number of CSV files – some of which are enormous – and only make them available via the website or over FTP.)

就本教程而言,我们将构建一个简单的电影搜索。 我已经创建了一个CSV文件,其中包含约2,000部电影,这些文件包含可下载的一系列关键字(例如,空间,夜晚和房屋),或者,如果您要创建自己的关键字,则可能需要查看Rotten Tomatoes API 。 (顺便说一句,但与此相关的是,IMDB使它们的数据可用,但散布在许多CSV文件中-其中一些是巨大的-并且只能通过网站或通过FTP获得。)

Before we write a command to import this data, let’s look at the basic create, update and delete operations on the SOLR search implementation using Solarium.

在编写用于导入此数据的命令之前,让我们看一下使用Solarium进行的SOLR搜索实现的基本创建更新删除操作。

将文档添加到搜索索引 (Adding Documents to the Search Index)

To add a document to the search index, you first need to create an update query instance:

要将文档添加到搜索索引,首先需要创建一个更新查询实例:

$update = $client->createUpdate();

Then create a document:

然后创建一个文档:

$doc = $update->createDocument();

Now you can treat the document ($doc) as if it were a stdClass and simply assign data as public properties:

现在,您可以将文档( $doc )当作stdClass对待,只需将数据分配为公共属性即可:

$doc->id = 123;
$doc->title = 'Some Movie';
$doc->cast = array('Sylvester Stallone', 'Marylin Monroe', 'Macauley Culkin');

…and so on, before adding the document to the update query:

…依此类推,然后将文档添加到更新查询中:

$update->addDocument($doc);

Then commit the update:

然后提交更新:

$update->addCommit();

Finally, to actually run the query you call update() on the client:

最后,要实际运行查询,请在客户端上调用update()

$result = $client->update($update);

If you wish to verify that you’ve successfully indexed some documents, visit the SOLR admin panel in your browser – typically http://localhost:8983/solr and click Core Admin, you’ll find the number of documents in the index listed as numDocs in the Index section.

如果您希望验证是否已成功为某些文档建立索引,请在浏览器中访问SOLR管理面板-通常为http://localhost:8983/solr并单击Core Admin,您将在列出的索引中找到文档数在“ Index部分中为numDocs

更新文件 (Updating Documents)

If you need to update a document in the index, you simply need to “re-add” it and – assuming it has the same unique identifier – SOLR will be smart enough to update it, rather than add a new one.

如果您需要更新索引中的文档,则只需“重新添加”它,并且-假设它具有相同的唯一标识符-SOLR将足够聪明来更新它,而不是添加一个新的。

删除文件 (Deleting Documents)

You can delete a document from the index using an update query, using syntax not too dissimilar to WHERE clauses in SQL. For example, to delete a document uniquely identified by the ID 123:

您可以使用更新查询,并且使用与SQL中的WHERE子句不太相似的语法,从索引中删除文档。 例如,要删除由ID 123唯一标识的文档:

// get an update query instance
$update = $client->createUpdate();

// add the delete query and a commit command to the update query
$update->addDeleteQuery('id:123');
$update->addCommit();

// this executes the query and returns the result
$result = $client->update($update);

Or you can be less specific:

或者您可以不那么具体:

// get an update query instance
$update = $client->createUpdate();

// add the delete query and a commit command to the update query
$update->addDeleteQuery('title:test*');
$update->addCommit();

// this executes the query and returns the result
$result = $client->update($update);

Note the use of a wildcard character – in other words: “delete all documents whose title starts with test”.

请注意使用通配符-换句话说:“删除标题以test开头的所有文档”。

用电影填充搜索索引 (Populating the Search Index with Movies)

Now we’ve looked at the fundamentals of indexing documents, let’s put some data into the index for our sample application.

现在,我们研究了索引文档的基础知识,让我们将一些数据放入示例应用程序的索引中。

Laravel makes it easy to build console commands, so let’s create one to import the contents of our movie CSV file and index them. We could also create corresponding database records at this point, but for the purposes of this exercise the indexed documents will contain everything we need.

Laravel使构建控制台命令变得容易,因此让我们创建一个以导入电影CSV文件的内容并为其编制索引。 此时我们也可以创建相应的数据库记录,但是出于本练习的目的,索引文档将包含我们需要的所有内容。

To create the command, enter the following into the command line:

要创建命令,请在命令行中输入以下内容:

php artisan command:make PopulateSearchIndexCommand

In the newly-generated file – app/commands/PopulateSearchIndexCommand.php – set the command’s name (i.e., what you enter on the command-line to run it) and the description:

在新生成的文件app/commands/PopulateSearchIndexCommand.php ,设置命令的名称(即,您在命令行上输入的名称以运行该命令)和说明:

/**
 * The console command name.
 *
 * @var string
 */
protected $name = 'search:populate';

/**
 * The console command description.
 *
 * @var string
 */
protected $description = 'Populates the search index with some sample movie data.';

Now we’ll use the fire() method to create the Solarium client, open the CSV, iterate through it and index each movie:

现在,我们将使用fire()方法创建Solarium客户端,打开CSV,对其进行迭代并为每部电影编制索引:

/**
 * Execute the console command.
 *
 * @return void
 */
public function fire()
{       
    $client = new \Solarium\Client(Config::get('solr'));

    // open up the CSV
    $csv_filepath = storage_path() . '/movies.csv';

    $fp = fopen($csv_filepath, 'r');

    // Now let's start importing
    while (($row = fgetcsv($fp, 1000, ";")) !== FALSE) {

        // get an update query instance
    $update = $client->createUpdate();

    // Create a document
        $doc = $update->createDocument();    

        // set the ID
    $doc->id = $row[0];

    // ..and the title
        $doc->title = $row[1];

        // The year, rating and runtime columns don't always have data
        if (strlen($row[2])) {
            $doc->year = $row[2];
        }
        if (strlen($row[3])) {
            $doc->rating = $row[3];
        }
        if (strlen($row[4])) {
            $doc->runtime = $row[4];
        }

        // set the synopsis
        $doc->synopsis = $row[5];

        // We need to create an array of cast members
        $cast = array();

        // Rows 6 through 10 contain (or don't contain) cast members' names
        for ($i = 6; $i <= 10; $i++) {
            if ((isset($row[$i])) && (strlen($row[$i]))) {
                $cast[] = $row[$i];
            }
        }

        // ...then we can assign the cast member array to the document
        $doc->cast = $cast;

        // Let's simply add and commit straight away.
        $update->addDocument($doc);
    $update->addCommit();

    // this executes the query and returns the result
    $result = $client->update($update);

    }

    fclose($fp);
}

Whilst this isn’t the slickest or most resilient piece of code, it’s a fairly academic exercise which we’re only planning to run once anyway. Ensure the CSV file is in the correct place – app/storage/movies.csv and run it:

虽然这不是最简洁或最有弹性的代码,但这是一个相当学术的练习,我们无论如何只打算运行一次。 确保CSV文件在正确的位置– app/storage/movies.csv并运行它:

php artisan search:populate

All being well, the index should now contain ~2,300 movies. You can check this via the admin interface.

一切都很好,索引现在应该可以包含约2,300部电影。 您可以通过管理界面进行检查。

In the next section we’ll start building the basic search in.

在下一节中,我们将开始构建基本搜索。

搜索表格 (The Search Form)

Let’s create the search form using Laravel’s Blade templating engine, along with the form builder. So, in app/views/home/index.blade.php:

让我们使用Laravel的Blade模板引擎以及表单构建器创建搜索表单。 因此,在app/views/home/index.blade.php

@extends('layouts.default')

@section('content')

<header>
    {{ Form::open(array('method' => 'GET')) }}
    <div class="input-group">
        {{ Form::text('q', Input::get('q'), array('class' => 'form-control input-lg', 'placeholder' => 'Enter your search term')) }}        
        <span class="input-group-btn">
            {{ Form::submit('Search', array('class' => 'btn btn-primary btn-lg')) }}            
        </span>
    </div>
    {{ Form::close() }}
</header>

@endsection

A basic page layout in app/views/layouts/default.blade.php:

app/views/layouts/default.blade.php基本页面布局:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Movie Search</title>

    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">

</head>
<body>
    <div class="container">
        <header id="header" class="row">        
            <div class="col-sm-12 col-md-12 col-lg-12">
                <h1>Movie Search</h1>
            </div>      
        </header>

        <div class="row">
            <div class="col-sm-12 col-md-12 col-lg-12">
                @yield('content')
            </div>
        </div>

        <hr />

        <footer id="footer">

        </footer>

    </div>

</body>
</html>

In app/controllers/HomeController.php:

app/controllers/HomeController.php

public function getIndex()
{
    return View::make('home.index');
}

Finally, replace the contents of app/routes.php with the following, to tell Laravel to use HomeController:

最后,用以下内容替换app/routes.php routes.php的内容,以告诉Laravel使用HomeController

<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
*/
Route::controller('/', 'HomeController');

Now we’re set up and ready to implement the basic search mechanism, which will be the subject of the next part in the series.

现在,我们已经准备好并准备实现基本的搜索机制,这将是本系列下一部分的主题。

摘要 (Summary)

In this second installment of a four part series, we’ve installed Solarium with a view to integrating Apache’s SOLR with a PHP application. We’ve set up an example application and indexed some data. In the next part we’ll start implementing the search mechanism.

在这个由四部分组成的系列的第二部分中,我们安装了Solarium,以期将Apache的SOLR与PHP应用程序集成。 我们已经建立了一个示例应用程序并为一些数据建立了索引。 在下一部分中,我们将开始实现搜索机制。

翻译自: https://www.sitepoint.com/using-solarium-solr-search-solarium-gui/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值