PHP操作Elasticsearch的客户端使用案例

现在通过我们前面的讲解,我们来通过php+Elasticsearch语法操作Query DSL代码如下

<?php
class search
{
    public function __construct()
    {
        $this->esUri = $host . ':' . $port . "/" . $index . "/" . $type. "/";
    }

    //demo
    public function demo()
    {
        $conditions = [
            ['field' => 'company', 'type' => 'like', 'value' => '春风'],
            ['field' => 'groupid', 'type' => 'between', 'value' => [4, 6]],
            ['field' => 'email', 'type' => '=', 'value' => 'jiaogun@139.com'],
        ];
        $page    = 1;
        $limit   = 20;
        $offset  = ($page > 0) ? ($page - 1) * $limit : 0;
        $columns = ['username', 'userid', 'groupid', 'company'];
        $order   = array('field' => 'userid', 'sort' => 'desc');
        $res     = $this->search($conditions, $offset, $limit, $columns, $order);
        var_dump($res);die();

    }

    //es搜索
    public function search($conditions = array(), $offset = 0, $limit = 20, $columns = array(), $order = array('field' => 'userid', 'sort' => 'desc'))
    {
        $params = [
            "query"   => [
                "filtered" => [
                    'filter' => [
                        'bool' => [
                            'must' => [
                            ],
                        ],
                    ],
                    "query"  => [
                        'bool' => [
                            'must' => [

                            ],
                        ],
                    ],
                ],
            ],
            'sort'    => [
                $order['field'] => [
                    'order' => $order['sort'],
                ],
            ],
            '_source' => $columns,
            'from'    => $offset,
            'size'    => $limit,
        ];
        if (!empty($conditions)) {
            foreach ($conditions as $v) {
                switch ($v['type']) {
                    case 'between':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['gt'] = $v['value'][0];
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['lt'] = $v['value'][1];
                        break;
                    case '>':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['gt'] = $v['value'];
                        break;
                    case '>=':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['gte'] = $v['value'];
                        break;
                    case '<':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['lt'] = $v['value'];
                        break;
                    case '<=':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['lte'] = $v['value'];
                        break;
                    case '=':
                        $params['query']['filtered']['filter']['bool']['must'][]['term'][$v['field']] = $v['value'];
                        break;
                    case '!=':
                        $params['query']['filtered']['filter']['bool']['must_not'][]['term'][$v['field']] = $v['value'];
                        break;
                    case 'in':
                        if (!empty($v['value']) && is_array($v['value'])) {
                            foreach ($v['value'] as $m => $n) {
                                $params['query']['filtered']['filter']['bool']['must'][] = array(
                                    'term' => array(
                                        $v['field'] => $n,
                                    ),
                                );
                            }
                        }
                        break;
                    case 'not in':
                        if (!empty($v['value']) && is_array($v['value'])) {
                            foreach ($v['value'] as $m => $n) {
                                $params['query']['filtered']['filter']['bool']['must_not'][] = array(
                                    'term' => array(
                                        $v['field'] => $n,
                                    ),
                                );
                            }
                        }
                        break;
                    case 'like':
                        $params['query']['filtered']['query']['bool']['must'][]['match'][$v['field']] = $v['value'];
                        unset($params['sort']);
                        $params['sort']['_score']['order'] = 'desc';
                        $params['sort']['userid']['order'] = 'desc';
                        break;
                    default:
                        return false;
                        break;
                }
            }
        }
        $res            = $this->getEs($params, true, $this->esUri . '_search/');
        $res            = json_decode($res, true);
        $reData['data'] = array();
        if (!empty($res['hits']['hits'])) {
            foreach ($res['hits']['hits'] as $k => $v) {
                $reData['data'][$k] = $v;
            }
        }
        $reData['count'] = !empty($res['hits']['total']) ? $res['hits']['total'] : 0;
        return $reData;
    }

    //es搜索 解决深度分页问题 按照userid asc排序
    public function searchAll($conditions = array(), $limit = 50, $columns = array(), $userid = 0)
    {
        $params = [
            "query"   => [
                "filtered" => [
                    'filter' => [
                        'bool' => [
                            'must' => [

                            ],
                        ],
                    ],
                    "query"  => [
                        'bool' => [
                            'must' => [
                                [
                                    'range' => [
                                        'userid' => [
                                            'gt' => $userid,
                                        ],
                                    ],
                                ],
                            ],
                        ],
                    ],
                ],
            ],
            'sort'    => [
                'userid' => [
                    'order' => 'asc',
                ],
            ],
            '_source' => $columns,
            'size'    => $limit,
        ];
        if (!empty($conditions)) {
            foreach ($conditions as $v) {
                switch ($v['type']) {
                    case 'between':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['gt'] = $v['value'][0];
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['lt'] = $v['value'][1];
                        break;
                    case '>':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['gt'] = $v['value'];
                        break;
                    case '>=':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['gte'] = $v['value'];
                        break;
                    case '<':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['lt'] = $v['value'];
                        break;
                    case '<=':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['lte'] = $v['value'];
                        break;
                    case '=':
                        $params['query']['filtered']['filter']['bool']['must'][]['term'][$v['field']] = $v['value'];
                        break;
                    case '!=':
                        $params['query']['filtered']['filter']['bool']['must_not'][]['term'][$v['field']] = $v['value'];
                        break;
                    case 'in':
                        if (!empty($v['value']) && is_array($v['value'])) {
                            foreach ($v['value'] as $m => $n) {
                                $params['query']['filtered']['filter']['bool']['must'][] = array(
                                    'term' => array(
                                        $v['field'] => $n,
                                    ),
                                );
                            }
                        }
                        break;
                    case 'not in':
                        if (!empty($v['value']) && is_array($v['value'])) {
                            foreach ($v['value'] as $m => $n) {
                                $params['query']['filtered']['filter']['bool']['must_not'][] = array(
                                    'term' => array(
                                        $v['field'] => $n,
                                    ),
                                );
                            }
                        }
                        break;
                    case 'like':
                        $params['query']['filtered']['query']['bool']['must'][]['match'][$v['field']] = $v['value'];
                        break;
                    default:
                        return false;
                        break;
                }
            }
        }
        $res            = $this->getEs($params, true, $this->esUri . '_search/');
        $res            = json_decode($res, true);
        $reData['data'] = array();
        if (!empty($res['hits']['hits'])) {
            foreach ($res['hits']['hits'] as $k => $v) {
                $reData['data'][$k] = $v;
            }
        }
        $reData['count'] = !empty($res['hits']['total']) ? $res['hits']['total'] : 0;
        return $reData;
    }

    //es统计数量
    public function count($conditions = array())
    {
        $params = [
            "query" => [
                "filtered" => [
                    'filter' => [
                        'bool' => [
                            'must' => [
                            ],
                        ],
                    ],
                    "query"  => [
                        'bool' => [
                            'must' => [

                            ],
                        ],
                    ],
                ],
            ],
        ];
        if (!empty($conditions)) {
            foreach ($conditions as $v) {
                switch ($v['type']) {
                    case 'between':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['gt'] = $v['value'][0];
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['lt'] = $v['value'][1];
                        break;
                    case '>':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['gt'] = $v['value'];
                        break;
                    case '>=':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['gte'] = $v['value'];
                        break;
                    case '<':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['lt'] = $v['value'];
                        break;
                    case '<=':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['lte'] = $v['value'];
                        break;
                    case '=':
                        $params['query']['filtered']['filter']['bool']['must'][]['term'][$v['field']] = $v['value'];
                        break;
                    case '!=':
                        $params['query']['filtered']['filter']['bool']['must_not'][]['term'][$v['field']] = $v['value'];
                        break;
                    case 'in':
                        if (!empty($v['value']) && is_array($v['value'])) {
                            foreach ($v['value'] as $m => $n) {
                                $params['query']['filtered']['filter']['bool']['must'][] = array(
                                    'term' => array(
                                        $v['field'] => $n,
                                    ),
                                );
                            }
                        }
                        break;
                    case 'not in':
                        if (!empty($v['value']) && is_array($v['value'])) {
                            foreach ($v['value'] as $m => $n) {
                                $params['query']['filtered']['filter']['bool']['must_not'][] = array(
                                    'term' => array(
                                        $v['field'] => $n,
                                    ),
                                );
                            }
                        }
                        break;
                    case 'like':
                        $params['query']['filtered']['query']['bool']['must'][]['match'][$v['field']] = $v['value'];
                        break;
                    default:
                        return false;
                        break;
                }
            }
        }
        $res   = $this->getEs($params, true, $this->esUri . '_count/');
        $res   = json_decode($res, true);
        $count = !empty($res['count']) ? $res['count'] : 0;
        return $count;
    }
    private function getEs($data = [], $ispost = true, $uri = "es地址")
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $uri);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        $result   = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($httpCode != 200) {
            var_dump($result);
            return false;
        } else {
            return $result;
        }
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Elasticsearch 提供了官方的 Java 客户端,可以通过它与 Elasticsearch 服务器进行交互。下面是一个简单的示例,展示如何使用 Elasticsearch Java 客户端: 1. 首先,确保你已经在项目中添加了 Elasticsearch Java 客户端的依赖。你可以在 Maven 或 Gradle 中添加以下依赖项: Maven: ```xml <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.15.0</version> </dependency> ``` Gradle: ```groovy implementation 'org.elasticsearch.client:elasticsearch-rest-high-level-client:7.15.0' ``` 2. 在代码中创建 Elasticsearch 客户端实例: ```java import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("localhost", 9200, "http"))); ``` 请确保将 "localhost" 和 9200 替换为你的 Elasticsearch 服务器的主机和端口。 3. 使用客户端执行操作,例如执行搜索操作: ```java import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.index.query.QueryBuilders; SearchRequest searchRequest = new SearchRequest("your_index_name"); searchRequest.source().query(QueryBuilders.matchQuery("your_field_name", "your_search_keyword")); SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); // 处理搜索响应 ``` 请将 "your_index_name" 替换为你的索引名称,将 "your_field_name" 替换为你要搜索的字段名称,将 "your_search_keyword" 替换为你要搜索的关键字。 这只是一个简单的示例,Elasticsearch Java 客户端提供了丰富的 API,可用于执行各种操作,如索引文档、更新文档、删除文档等。你可以参考 Elasticsearch Java 客户端的官方文档来了解更多信息:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值