PHP에서 Elasticsearch를 사용하는 방법

不言
풀어 주다: 2023-04-02 19:28:01
원래의
8910명이 탐색했습니다.

이 글은 주로 PHP에서 Elasticsearch를 사용하는 방법을 소개하는데, 이는 어느 정도 참고할만한 가치가 있습니다. 이제는 모든 사람과 공유합니다. 도움이 필요한 친구들이 참고할 수 있습니다.

강좌 추천 →: "Elasticsearch 전체 텍스트 검색 연습 "(실용 동영상)

과정 "수백만 개의 데이터 동시성 솔루션(이론 + 실전 전투)"

PHP에서 Elasticsearch를 사용

composer require elasticsearch/elasticsearch
로그인 후 복사

하면 자동으로 해당 버전이 로드됩니다! 내 PHP는 5.6이며 자동으로 5.3 Elasticsearch 버전을 로드합니다!

Using version ^5.3 for elasticsearch/elasticsearch
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 4 installs, 0 updates, 0 removals
  - Installing react/promise (v2.7.0): Downloading (100%)         
  - Installing guzzlehttp/streams (3.0.0): Downloading (100%)         
  - Installing guzzlehttp/ringphp (1.1.0): Downloading (100%)         
  - Installing elasticsearch/elasticsearch (v5.3.2): Downloading (100%)         
Writing lock file
Generating autoload files
로그인 후 복사

사용이 간편함

<?php

class MyElasticSearch
{
    private $es;
    // 构造函数
    public function __construct()
    {
        include(&#39;../vendor/autoload.php&#39;);
        $params = array(
            &#39;127.0.0.1:9200&#39;
        );
        $this->es = \Elasticsearch\ClientBuilder::create()->setHosts($params)->build();
    }

    public function search() {
        $params = [
            &#39;index&#39; => &#39;megacorp&#39;,
            &#39;type&#39; => &#39;employee&#39;,
            &#39;body&#39; => [
                &#39;query&#39; => [
                    &#39;constant_score&#39; => [ //非评分模式执行
                        &#39;filter&#39; => [ //过滤器,不会计算相关度,速度快
                            &#39;term&#39; => [ //精确查找,不支持多个条件
                                &#39;about&#39; => &#39;谭&#39;
                            ]
                        ]

                    ]
                ]
            ]
        ];

        $res = $this->es->search($params);

        print_r($res);
    }
}
로그인 후 복사
<?php
require "./MyElasticSearch.php";

$es = new MyElasticSearch();

$es->search();
로그인 후 복사

실행 결과

Array
(
    [took] => 2
    [timed_out] => 
    [_shards] => Array
        (
            [total] => 5
            [successful] => 5
            [skipped] => 0
            [failed] => 0
        )

    [hits] => Array
        (
            [total] => 1
            [max_score] => 1
            [hits] => Array
                (
                    [0] => Array
                        (
                            [_index] => megacorp
                            [_type] => employee
                            [_id] => 3
                            [_score] => 1
                            [_source] => Array
                                (
                                    [first_name] => 李
                                    [last_name] => 四
                                    [age] => 24
                                    [about] => 一个PHP程序员,热爱编程,谭康很帅,充满激情。
                                    [interests] => Array
                                        (
                                            [0] => 英雄联盟
                                        )

                                )

                        )

                )

        )

)
로그인 후 복사

공식적인 예는 다음과 같습니다.

초기화

require &#39;../vendor/autoload.php&#39;;
use Elasticsearch\ClientBuilder;
$client = ClientBuilder::create()->build();
로그인 후 복사

구성 추가

$hosts = [
    &#39;127.0.01:9200&#39;,         // IP + Port
];

$client = ClientBuilder::create()           // Instantiate a new ClientBuilder
->setHosts($hosts)      // Set the hosts
->build();              // Build the client object
로그인 후 복사

또는

$hosts = [
    &#39;127.0.01:9200&#39;,         // IP + Port
];

$clientBuilder = ClientBuilder::create();   // Instantiate a new ClientBuilder
$clientBuilder->setHosts($hosts);           // Set the hosts
$client = $clientBuilder->build();          // Build the client object
로그인 후 복사

문서 삽입

// Index 一个文档
$params = [
    &#39;index&#39; => &#39;my_index&#39;,
    &#39;type&#39; => &#39;my_type&#39;,
    &#39;id&#39; => &#39;my_id&#39;,
    &#39;body&#39; => [&#39;testField&#39; => &#39;abc&#39;]
];

$response = $client->index($params);
print_r($response);
로그인 후 복사

문서 가져오기

$params = [
    &#39;index&#39; => &#39;my_index&#39;,
    &#39;type&#39; => &#39;my_type&#39;,
    &#39;id&#39; => &#39;my_id&#39;
];

$response = $client->get($params);
print_r($response);
로그인 후 복사

문서 쿼리

$params = [
    &#39;index&#39; => &#39;my_index&#39;,
    &#39;type&#39; => &#39;my_type&#39;,
    &#39;body&#39; => [
        &#39;query&#39; => [
            &#39;match&#39; => [
                &#39;testField&#39; => &#39;abc&#39;
            ]
        ]
    ]
];

$response = $client->search($params);
print_r($response);
로그인 후 복사

문서 삭제

$params = [
    &#39;index&#39; => &#39;my_index&#39;,
    &#39;type&#39; => &#39;my_type&#39;,
    &#39;id&#39; => &#39;my_id&#39;
];

$response = $client->delete($params);
print_r($response);
로그인 후 복사

결과는 다음과 같습니다

Array
(
    [_index] => my_index
    [_type] => my_type
    [_id] => my_id
    [_version] => 3
    [result] => deleted
    [_shards] => Array
        (
            [total] => 2
            [successful] => 1
            [failed] => 0
        )

    [_seq_no] => 2
    [_primary_term] => 1
)
로그인 후 복사

색인 삭제

$deleteParams = [
    &#39;index&#39; => &#39;my_index&#39;
];
$response = $client->indices()->delete($deleteParams);
print_r($response);
로그인 후 복사

색인 만들기

$params = [
    &#39;index&#39; => &#39;my_index&#39;,
    &#39;body&#39; => [
        &#39;settings&#39; => [
            &#39;number_of_shards&#39; => 2,
            &#39;number_of_replicas&#39; => 0
        ]
    ]
];

$response = $client->indices()->create($params);
print_r($response);
로그인 후 복사

위 내용은 모두의 학습에 도움이 되기를 바랍니다. 더 많은 관련 콘텐츠를 보려면 PHP 중국어 웹사이트를 주목하세요!

관련 권장사항:

PHP 데이터 구조 기본 스택

Beanstalkd 운영을 위한 PHP 메서드 및 매개변수 주석

위 내용은 PHP에서 Elasticsearch를 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!