简体   繁体   English

从 php 中的索引 elasticsearch 获取所有数据

[英]Get all data from index elasticsearch in php

I am doing a test with elasticsearch to implement it in my project.我正在使用 elasticsearch 进行测试以在我的项目中实现它。

I use CodeIgniter for my website.我在我的网站上使用 CodeIgniter。 I found this link: confact/elasticsearch-codeigniter-library我找到了这个链接: confact/elasticsearch-codeigniter-library

I use this library in my project.我在我的项目中使用这个库。 Which works perfectly.效果很好。 Now my question is how can I return all my data from the index?现在我的问题是如何从索引中返回所有数据?

In principle, when I use Postman I type this link for my search: http://localhost:9200/my_index/_search?q=test and I find my data well.原则上,当我使用 Postman 时,我输入此链接进行搜索: http://localhost:9200/my_index/_search?q=test并且我找到了我的数据。

In my code, this is what we have:在我的代码中,这就是我们所拥有的:

my library elasticsearch.php:我的图书馆 elasticsearch.php:

    <?php
/**
 * Elasticsearch Library
 *
 * @package OpenLibs
 * 
 */
class ElasticSearch
{
    public $index;

    /**
     * constructor setting the config variables for server ip and index.
     */

    public function __construct()
    {
        $ci = &get_instance();
        $ci -> config -> load("elasticsearch");
        $this -> server = $ci -> config -> item('es_server');
        $this -> index = $ci -> config -> item('index');
    }
    /**
     * Handling the call for every function with curl
     * 
     * @param type $path
     * @param type $method
     * @param type $data
     * 
     * @return type
     * @throws Exception
     */

    private function call($path, $method = 'GET', $data = null)
    {
        if (!$this -> index) {
            throw new Exception('$this->index needs a value');
        }

        $url = $this -> server . '/' . $this -> index . '/' . $path;

        $headers = array('Accept: application/json', 'Content-Type: application/json', );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        switch($method) {
            case 'GET' :
                break;
            case 'POST' :
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                break;
            case 'PUT' :
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
                break;
            case 'DELETE' :
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
                break;
        }

        $response = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        return json_decode($response, true);
    }


    /**
     * create a index with mapping or not
     * 
     * @param json $map
     */

    public function create($map = false)
    {
        if (!$map) {
            $this -> call(null, 'PUT');
        } else {
            $this -> call(null, 'PUT', $map);
        }
    }

    /**
     * get status
     * 
     * @return array
     */

    public function status()
    {
        return $this -> call('_status');
    }

    /**
     * count how many indexes it exists
     * 
     * @param string $type
     * 
     * @return array
     */

    public function count($type)
    {
        return $this -> call($type . '/_count?' . http_build_query(array(null => '{matchAll:{}}')));
    }

    /**
     * set the mapping for the index
     * 
     * @param string $type
     * @param json   $data
     * 
     * @return array
     */

    public function map($type, $data)
    {
        return $this -> call($type . '/_mapping', 'PUT', $data);
    }

    /**
     * set the mapping for the index
     * 
     * @param type $type
     * @param type $id
     * @param type $data
     * 
     * @return type
     */

    public function add($type, $id, $data)
    {
        return $this -> call($type . '/' . $id, 'PUT', $data);
    }

    /**
     * delete a index
     * 
     * @param type $type 
     * @param type $id 
     * 
     * @return type 
     */

    public function delete($type, $id)
    {
        return $this -> call($type . '/' . $id, 'DELETE');
    }

    /**
     * make a simple search query
     * 
     * @param type $type
     * @param type $q
     * 
     * @return type
     */

    public function query($type, $q)
    {
        return $this -> call($type . '/_search?' . http_build_query(array('q' => $q)));
    }

    /**
     * make a advanced search query with json data to send
     * 
     * @param type $type
     * @param type $query
     * 
     * @return type
     */

    public function advancedquery($type, $query)
    {
        return $this -> call($type . '/_search', 'POST', $query);
    }

    /**
     * make a search query with result sized set
     * 
     * @param string  $type  what kind of type of index you want to search
     * @param string  $query the query as a string
     * @param integer $size  The size of the results
     * 
     * @return array
     */

    public function query_wresultSize($type, $query, $size = 999)
    {
        return $this -> call($type . '/_search?' . http_build_query(array('q' => $q, 'size' => $size)));
    }

    /**
     * get one index via the id
     * 
     * @param string  $type The index type
     * @param integer $id   the indentifier for a index
     * 
     * @return type
     */

    public function get($type, $id)
    {
        return $this -> call($type . '/' . $id, 'GET');
    }

    /**
     * Query the whole server
     * 
     * @param type $query
     * 
     * @return type
     */

    public function query_all($query)
    {
        return $this -> call('_search?' . http_build_query(array('q' => $query)));
    }

    /**
     * get similar indexes for one index specified by id - send data to add filters or more
     * 
     * @param string  $type
     * @param integer $id
     * @param string  $fields
     * @param string  $data 
     * 
     * @return array 
     */

    public function morelikethis($type, $id, $fields = false, $data = false)
    {
        if ($data != false && !$fields) {
            return $this -> call($type . '/' . $id . '/_mlt', 'GET', $data);
        } else if ($data != false && $fields != false) {
            return $this -> call($type . '/' . $id . '/_mlt?' . $fields, 'POST', $data);
        } else if (!$fields) {
            return $this -> call($type . '/' . $id . '/_mlt');
        } else {
            return $this -> call($type . '/' . $id . '/_mlt?' . $fields);
        }
    }

    /**
     * make a search query with result sized set
     * 
     * @param type $query
     * @param type $size
     * 
     * @return type
     */
    public function query_all_wresultSize($query, $size = 999)
    {
        return $this -> call('_search?' . http_build_query(array('q' => $query, 'size' => $size)));
    }

    /**
     * make a suggest query based on similar looking terms
     * 
     * @param type $query
     * 
     * @return array
     */
    public function suggest($query)
    {
        return $this -> call('_suggest', 'POST', $query);
    }

}

And in my controller:在我的 controller 中:

public function search() 
{
    $q= '';
    $this->elasticsearch->index = 'my_index';
    $data = $this->elasticsearch->query_all($q);
    var_dump($data);
}

Unfortunately, I can not find my data in this case.不幸的是,在这种情况下我找不到我的数据。 Am I cheating somewhere?我在哪里作弊吗?

If anyone could help me, it would help me a lot.如果有人可以帮助我,那将对我有很大帮助。

Thank you:*谢谢:*

Assuming you have your form in your view, you should do something like this:假设您的视图中有表单,您应该执行以下操作:

public function search() 
{
    $param = $this->input->get('q');
    $this->elasticsearch->index = 'my_index';     
    $data = $this->elasticsearch->query_all_wresultSize($param);        
    $response = json_decode(json_encode($data),true);
    $hits = count($response['hits']['hits']);
    var_dump($hits);
    $result = null;
    $i = 0;
    while ($i < $hits) {
    $result[$i] = $response['hits']['hits'][$i]['_source'];
    $i++;
    }
    foreach ($result as $key => $value) {
        echo $value['My_field_id'] . " : ";
        echo $value['My_field_name'] . "<br>";
    }
}

Assuming you are using elasticsearch php lib假设您使用的是 elasticsearch php 库

public function array_pluck($array, $key) {
        return array_map(function($v) use ($key) {
          return is_object($v) ? $v->$key : $v[$key];
        }, $array);
    }

For searching through a document you use this要搜索文档,请使用此

$params = [
    'index' => 'my_index',
    'body'  => [
        'query' => [
            'match' => [
                'testField' => 'abc'
            ]
        ]
    ]
];

$response = $client->search($params);
print_r($response);

/**
Array
(
    [took] => 1
    [timed_out] =>
    [_shards] => Array
        (
            [total] => 5
            [successful] => 5
            [failed] => 0
        )

    [hits] => Array
        (
            [total] => 1
            [max_score] => 0.30685282
            [hits] => Array
                (
                    [0] => Array
                        (
                            [_index] => my_index
                            [_type] => _doc
                            [_id] => my_id
                            [_score] => 0.30685282
                            [_source] => Array
                                (
                                    [testField] => abc
                                )
                        )
                )
        )
)
*/

use the array pluck method(I got it from laravel) to extract all the hits you've got,in above there's only 1 hit but this works for multiple hits as well使用数组 pluck 方法(我从 laravel 获得)提取你得到的所有命中,在上面只有 1 个命中,但这也适用于多个命中

$source_data = $this->array_pluck( $response['hits']['hits'], '_source' );

It will return a array the values它将返回一个数组值

/**
[0] => Array
                        (
                            [_index] => my_index
                            [_type] => _doc
                            [_id] => my_id
                            [_score] => 0.30685282
                            [_source] => Array
                                (
                                    [testField] => abc
                                )
                        )
*/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM