Home  >  Q&A  >  body text

Retranslated as: "PHP syntax ElasticSearch"

<p>我是ElasticSearch的新手,对查询的工作原理不太了解... 我的索引示例</p> <pre class="brush:php;toolbar:false;">{ "_index" : "indexing001", "_type" : "_doc", "_id" : "3", "_version" : 1, "_seq_no" : 242, "_primary_term" : 2, "found" : true, "_source" : { "type" : 1, "sub_type" : null, "user" : { "id" : 1, "name" : "tk6z2 gcnouvqmr" }, "editor_user" : [ ], "content" : [ { "title" : "Title #3", "short_text" : "Article #3 short text", "full_text" : "Article #3 full text", "locale" : "de-DE" } ], "flags" : [ ], "location" : [ ], "start_date" : 1658793600, "end_date" : 1658793600, "_users" : [ ] } }</pre> <p>我想查询文本以匹配字段<code>content.title</code>和<code>content.short_text</code>,通过<code>_users</code>字段查询用户。例如,我的函数是:</p> <pre class="brush:php;toolbar:false;">public static function search( string $text = '', int $user = 0 ): array { try { $model = new someModelClass(); $fields = [ 'content.title', 'content.short_text', ]; $result = $model::find()->query( [ 'bool' => [ 'should' => [ 'multi_match' => [ 'query' => $text, 'fields' => $fields, ], ], 'filter' => [ [ 'term' => [ '_users.id' => $user ] ], [ 'term' => [ '_users' => [] ] ], ] ], ] )->all(); return $result; } catch ( Exception $e ) { throw new Exception( $e->getMessage() ); } }</pre> <p>将其转换为SQL应该是这样的:<code>SELECT * FROM 'indexing001' WHERE (content.title LIKE %search% OR content.short_text LIKE %search%) AND (users.id = 1 OR users = '')</code> 如何在ElasticSearch查询中编写它? 提前感谢!</p>
P粉176203781P粉176203781441 days ago529

reply all(1)I'll reply

  • P粉421119778

    P粉4211197782023-08-29 00:46:01

    In this case, I recommend using the Elasticsearch-PHP client.

    Please use composer to install the appropriate client.

    For the following matching query

    curl -XGET 'localhost:9200/my_index/_search' -d '{
        "query" : {
            "match" : {
                "testField" : "abc"
            }
        }
    }'

    You can query it in your PHP script as shown below

    $params = [
        'index' => 'my_index',
        'body'  => [
            'query' => [
                'match' => [
                    'testField' => 'abc'
                ]
            ]
        ]
    ];
    
    $results = $client->search($params);
    

    See more actions here.

    reply
    0
  • Cancelreply