Elastic 搜索和 Codeigniter (PHP)

发布于 2024-12-15 10:25:37 字数 3320 浏览 0 评论 0原文

我正在尝试将 ElasticSearch 与 Codeigniter 框架结合使用。

我所做的只是安装 ElasticSearch 并将在网上找到的一个好的 PHP 库复制(:P)到 CI 库:

    class Elasticsearch {

  public $config_file = 'elasticsearch';
  public $index;

  function __construct($index = false){
      $CI =& get_instance();
      $CI->config->load($this->config_file);
      $this->server = $CI->config->item('es_server');

  }

  function call($path, $http = array()){
    if (!$this->index) throw new Exception('$this->index needs a value');
    return json_decode(file_get_contents($this->server . '/' . $this->index . '/' . $path, NULL, stream_context_create(array('http' => $http))));
  }

  //curl -X PUT http://localhost:9200/{INDEX}/
  function create(){
     $this->call(NULL, array('method' => 'PUT'));
  }

  //curl -X DELETE http://localhost:9200/{INDEX}/
  function drop(){
     $this->call(NULL, array('method' => 'DELETE'));
  }

  //curl -X GET http://localhost:9200/{INDEX}/_status
  function status(){
    return $this->call('_status');
  }

  //curl -X GET http://localhost:9200/{INDEX}/{TYPE}/_count -d {matchAll:{}}
  function count($type){
    return $this->call($type . '/_count', array('method' => 'GET', 'content' => '{ matchAll:{} }'));
  }

  //curl -X PUT http://localhost:9200/{INDEX}/{TYPE}/_mapping -d ...
  function map($type, $data){
    return $this->call($type . '/_mapping', array('method' => 'PUT', 'content' => $data));
  }

  //curl -X PUT http://localhost:9200/{INDEX}/{TYPE}/{ID} -d ...
  function add($type, $id, $data){
   echo  $this->call($type . '/' . $id, array('method' => 'PUT', 'content' => $data));
  }

  //curl -X GET http://localhost:9200/{INDEX}/{TYPE}/_search?q= ...
  function query($type, $q){
    return $this->call($type . '/_search?' . http_build_query(array('q' => $q)));
  }
}

然后我尝试创建索引并简单地检索它们:

$this->load->library('elasticsearch');
                 $this->elasticsearch->index = 'comments';
                 $this->elasticsearch->create();
                 $data = '{author:jhon,datetime:2001-09-09 00:02:04}';
                 $this->elasticsearch->add($type ='details',$id = '1',$data);

当我运行此代码时,它会显示错误:

A PHP Error was encountered

Severity: Warning

Message: file_get_contents(http://localhost:9200/comments/) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request

Filename: libraries/Elasticsearch.php

Line Number: 19
A PHP Error was encountered

Severity: Notice

Message: file_get_contents() [function.file-get-contents]: Content-type not specified assuming application/x-www-form-urlencoded

Filename: libraries/Elasticsearch.php

Line Number: 19
A PHP Error was encountered

Severity: Warning

Message: file_get_contents(http://localhost:9200/comments/details/1) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request

Filename: libraries/Elasticsearch.php

Line Number: 19

我是吗?我弄错/错过了什么吗?抱歉,但我是 elasticsearch 的新手,对 php 也有一点了解:P

因为如果我去:

http://localhost:9200/comments/details/1

//it prints in window
 {"_index":"comments","_type":"details","_id":"1","exists":false}

I'm trying using ElasticSearch with Codeigniter framework.

What i did is just install ElasticSearch and copyed ( :P ) a good PHP library found on the web to CI libraries:

    class Elasticsearch {

  public $config_file = 'elasticsearch';
  public $index;

  function __construct($index = false){
      $CI =& get_instance();
      $CI->config->load($this->config_file);
      $this->server = $CI->config->item('es_server');

  }

  function call($path, $http = array()){
    if (!$this->index) throw new Exception('$this->index needs a value');
    return json_decode(file_get_contents($this->server . '/' . $this->index . '/' . $path, NULL, stream_context_create(array('http' => $http))));
  }

  //curl -X PUT http://localhost:9200/{INDEX}/
  function create(){
     $this->call(NULL, array('method' => 'PUT'));
  }

  //curl -X DELETE http://localhost:9200/{INDEX}/
  function drop(){
     $this->call(NULL, array('method' => 'DELETE'));
  }

  //curl -X GET http://localhost:9200/{INDEX}/_status
  function status(){
    return $this->call('_status');
  }

  //curl -X GET http://localhost:9200/{INDEX}/{TYPE}/_count -d {matchAll:{}}
  function count($type){
    return $this->call($type . '/_count', array('method' => 'GET', 'content' => '{ matchAll:{} }'));
  }

  //curl -X PUT http://localhost:9200/{INDEX}/{TYPE}/_mapping -d ...
  function map($type, $data){
    return $this->call($type . '/_mapping', array('method' => 'PUT', 'content' => $data));
  }

  //curl -X PUT http://localhost:9200/{INDEX}/{TYPE}/{ID} -d ...
  function add($type, $id, $data){
   echo  $this->call($type . '/' . $id, array('method' => 'PUT', 'content' => $data));
  }

  //curl -X GET http://localhost:9200/{INDEX}/{TYPE}/_search?q= ...
  function query($type, $q){
    return $this->call($type . '/_search?' . http_build_query(array('q' => $q)));
  }
}

then i'm trying creating indexes and simply retrieve them:

$this->load->library('elasticsearch');
                 $this->elasticsearch->index = 'comments';
                 $this->elasticsearch->create();
                 $data = '{author:jhon,datetime:2001-09-09 00:02:04}';
                 $this->elasticsearch->add($type ='details',$id = '1',$data);

when i run this code it show me errors:

A PHP Error was encountered

Severity: Warning

Message: file_get_contents(http://localhost:9200/comments/) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request

Filename: libraries/Elasticsearch.php

Line Number: 19
A PHP Error was encountered

Severity: Notice

Message: file_get_contents() [function.file-get-contents]: Content-type not specified assuming application/x-www-form-urlencoded

Filename: libraries/Elasticsearch.php

Line Number: 19
A PHP Error was encountered

Severity: Warning

Message: file_get_contents(http://localhost:9200/comments/details/1) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request

Filename: libraries/Elasticsearch.php

Line Number: 19

does i'm mistaking/missed somenthing? sorry but i'm newbie about elasticsearch and also a little bit with php :P

cause if i go to:

http://localhost:9200/comments/details/1

//it prints in window
 {"_index":"comments","_type":"details","_id":"1","exists":false}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

云之铃。 2024-12-22 10:25:37

我不太确定,但我的猜测是您对 add() 的调用:

$this->elasticsearch->add($type ='details',$id = '1',$data);

您不想在此处设置值。我假设您会在 HTTP 错误请求之前收到 php 错误,但我会首先尝试:

$this->elasticsearch->add('details','1',$data);

您的 add() 方法已经知道参数代表什么,因此您只需要传递详细信息。

此外

您的 json 格式可能不正确。

// change
$data = '{author:jhon,datetime:2001-09-09 00:02:04}';

// to
$data = '{author:"jhon",datetime:2001-09-09 00:02:04}';

I'm not quite sure, but my guess would be your call to add():

$this->elasticsearch->add($type ='details',$id = '1',$data);

You don't want to be setting values here. I would assume you'd get a php error before an HTTP bad request, but I would try this first:

$this->elasticsearch->add('details','1',$data);

Your add() method already knows what the arguments represent, so you just need to pass the details.

Also

It looks like your json might be malformed.

// change
$data = '{author:jhon,datetime:2001-09-09 00:02:04}';

// to
$data = '{author:"jhon",datetime:2001-09-09 00:02:04}';
壹場煙雨 2024-12-22 10:25:37

一个老问题,但值得更新。
使用此插件

将您的 composer.json 文件放入应用程序文件夹中:

{
     "require": {
     "elasticsearch/elasticsearch": "~2.0"
     }
}

要安装 composer 和 elasticsearch 插件,请执行在 bash shell 中执行以下命令:

curl -s http://getcomposer.org/installer | php
php composer.phar install --no-dev

安装 php-curl 并重新启动 apache 服务器:

sudo apt-get install php5-curl
sudo service apache2 restart

在库文件夹 (codeigniter) 中创建一个 Elasticsearch.php 文件,并将以下代码放入其中

<?php 
use Elasticsearch\ClientBuilder;

class Elasticsearch{

    public $client;

    public function __construct(){
        $this->client = ClientBuilder::create()->build();
    } 
}

:可以通过以下方式自动加载elasticsearch在 config 文件夹中编辑 autoload.php:

$autoload['libraries'] = array(/*[some other library,]*/'elasticsearch');

然后在您的模型/控制器中使用:

$this->elasticsearch->client->index($params);

An old question, but deserves an update.
Use this plugin.

Put your composer.json file in the application folder:

{
     "require": {
     "elasticsearch/elasticsearch": "~2.0"
     }
}

To install composer and elasticsearch plugin execute these commands in bash shell:

curl -s http://getcomposer.org/installer | php
php composer.phar install --no-dev

Install php-curl and restart apache server:

sudo apt-get install php5-curl
sudo service apache2 restart

Create a Elasticsearch.php file in the libraries folder (codeigniter), and put this code inside:

<?php 
use Elasticsearch\ClientBuilder;

class Elasticsearch{

    public $client;

    public function __construct(){
        $this->client = ClientBuilder::create()->build();
    } 
}

You can autoload elasticsearch by editing autoload.php in config folder:

$autoload['libraries'] = array(/*[some other library,]*/'elasticsearch');

Then in your model/controller use:

$this->elasticsearch->client->index($params);
愚人国度 2024-12-22 10:25:37

您提供的 PHP 库未定义内容类型,这就是您收到消息的原因:“未指定内容类型”。

请在此处检查 PHP 库并浏览 README.txt。它有详细的注释,对初学者很有用,您可能需要仔细阅读它们:
https://github.com/niranjan-uma-shankar/Elasticsearch-PHP-class

如果您使用这个库,那么您可以像这样初始化该类:

$this->load->library('elasticsearch');
$elasticSearch = new $this->elasticsearch;
$elasticsearch->index = 'comments';
$elasticsearch->type = 'details';
$elasticsearch->create();
$data = '{"author" : "jhon", "datetime" : "2001-09-09 00:02:04"}';
$elasticsearch->add(1, $data);

The PHP library that you have given is not defining content-type, that's why you are getting the message: "Content-type not specified".

Check the PHP library here and also go through the README.txt. It has detailed notes which will be useful to beginners and you may want to go through them:
https://github.com/niranjan-uma-shankar/Elasticsearch-PHP-class

If you use this library, then you can initialize the class like this:

$this->load->library('elasticsearch');
$elasticSearch = new $this->elasticsearch;
$elasticsearch->index = 'comments';
$elasticsearch->type = 'details';
$elasticsearch->create();
$data = '{"author" : "jhon", "datetime" : "2001-09-09 00:02:04"}';
$elasticsearch->add(1, $data);
挽袖吟 2024-12-22 10:25:37

调用不带引号(单引号或双引号)传递参数的函数:

$this->elasticsearch->add(details, 1, $data);

此外,对我来说,使用数组然后将其编码为 json 对象更容易:

$data = array('author' => 'john', 'datetime' => '2001-09-09 00:02:04');
$this->elasticsearch->add(details, 1, json_encode($data));

Call the functions passing the parameters without quotes (single or double):

$this->elasticsearch->add(details, 1, $data);

In addition, for me it's easier to work with arrays and then encode it into json objects:

$data = array('author' => 'john', 'datetime' => '2001-09-09 00:02:04');
$this->elasticsearch->add(details, 1, json_encode($data));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文