GithubHelp home page GithubHelp logo

manticoresearch-php's Introduction

manticoresearch-php

Build Status Scrutinizer Code Quality codecov.io Latest Stable Version License Slack

Total Downloads Monthly Downloads Daily Downloads composer.lock

GitHub Code Size GitHub Repo Size GitHub Last Commit GitHub Activity GitHub Issues

Official PHP client for Manticore Search.

❗ WARNING: this is a development version of the client. The latest release's readme is https://github.com/manticoresoftware/manticoresearch-php/tree/3.1.0

Features

  • One to one mapping with the HTTP API
  • connection pools with pluggable selection strategy. Defaults to static round robin
  • pluggable PSR/Log interface
  • pluggable transport protocols.
  • persistent connections

Requirements

Requires PHP 7.1 or greater with the native JSON extension. Default transport handler uses the cURL extension.

Minimum Manticore Search version is 2.5.1 with HTTP protocol enabled.

Manticore Search manticoresearch-php PHP
>= 6.2.0 3.1.x >= 7.4, >=8.0
>= 6.2.0 3.0.x >= 7.4, >=8.0
>= 6.0.4 3.0.x >= 7.1, >=8.0
>= 4.2.1 2.0.x, 2.1.x, 2.2.x >= 7.1, >=8.0
>= 4.0.2 1.7.x, 1.8.x >= 7.1, >=8.0
>= 3.5.2 1.6.x >= 7.1, >=8.0
>= 3.5.0 1.5.x >= 7.1, <8.0
>= 3.5.0 1.4 >= 7.1, <8.0
<= 3.4.x 1.3 >= 7.1, <8.0
>= 2.5.1, <3.4.0 1.2 >= 7.1, <8.0

Documentation

Full documentation is available in docs folder.

Manticore Search server documentation: https://manual.manticoresearch.com/.

Getting Started

Install the Manticore Search PHP client using composer package manager:

composer require manticoresoftware/manticoresearch-php

Initiate an index:

require_once __DIR__ . '/vendor/autoload.php';

$config = ['host'=>'127.0.0.1','port'=>9308];
$client = new \Manticoresearch\Client($config);
$index = $client->index('movies');

Create the index:

$index->create([
    'title'=>['type'=>'text'],
    'plot'=>['type'=>'text'],
    '_year'=>['type'=>'integer'],
    'rating'=>['type'=>'float']
    ]);

Add a document:

$index->addDocument([
        'title' => 'Star Trek: Nemesis',
        'plot' => 'The Enterprise is diverted to the Romulan homeworld Romulus, supposedly because they want to negotiate a peace treaty. Captain Picard and his crew discover a serious threat to the Federation once Praetor Shinzon plans to attack Earth.',
        '_year' => 2002,
        'rating' => 6.4
        ],
    1);

Add several documents at once:

$index->addDocuments([
        ['id'=>2,'title'=>'Interstellar','plot'=>'A team of explorers travel through a wormhole in space in an attempt to ensure humanity\'s survival.','_year'=>2014,'rating'=>8.5],
        ['id'=>3,'title'=>'Inception','plot'=>'A thief who steals corporate secrets through the use of dream-sharing technology is given the inverse task of planting an idea into the mind of a C.E.O.','_year'=>2010,'rating'=>8.8],
        ['id'=>4,'title'=>'1917 ','plot'=>' As a regiment assembles to wage war deep in enemy territory, two soldiers are assigned to race against time and deliver a message that will stop 1,600 men from walking straight into a deadly trap.','_year'=>2018,'rating'=>8.4],
        ['id'=>5,'title'=>'Alien','plot'=>' After a space merchant vessel receives an unknown transmission as a distress call, one of the team\'s member is attacked by a mysterious life form and they soon realize that its life cycle has merely begun.','_year'=>1979,'rating'=>8.4]
    ]); 

Perform a search:

$results = $index->search('space team')->get();

foreach($results as $doc) {
   echo 'Document:'.$doc->getId()."\n";
   foreach($doc->getData() as $field=>$value)
   {   
        echo $field.": ".$value."\n";
   }
}

Result:

Document:2
year: 2014
rating: 8.5
title: Interstellar
plot: A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.

A text search with attribute filters:

$results = $index->search('space team')
                 ->filter('_year','gte',2000)
                 ->filter('rating','gte',8.0)
                 ->sort('_year','desc')
                 ->get();

foreach($results as $doc) {
    echo 'Document:'.$doc->getId()."\n";
    foreach($doc->getData() as $field=>$value)
    {   
        echo $field.": ".$value."\n";
    }
}

Update documents:

By document id:

$index->updateDocument(['_year'=>2019],4);

By query:

$index->updateDocument(['_year'=>2019],['match'=>['*'=>'team']]);

Get index schema:

$index->describe();

Drop index:

$index->drop();

The above will fail if the index does not exist. To get around this pass a parameter of true, which cause the failure to be silent.

$index->drop(true);

License

Manticore Search PHP Client is an open-source software licensed under the MIT license

manticoresearch-php's People

Contributors

acya-skulskaya avatar adriannuta avatar airolg avatar aivchen avatar andrey-tech avatar donhardman avatar evilfreelancer avatar geatech avatar gordonbanderson avatar manticoresearch avatar marios88 avatar markomilivojevic avatar nick-s-2018 avatar nurieff avatar sanikolaev avatar tinigin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

manticoresearch-php's Issues

Issue with umlauts when using the keywords call

Hi,

I'm having some trouble with the keywords regarding german umlauts. If I issue the call with:

$keywords = $index->keywords(implode("* ", $query)."*", []);

Which results in this request being sent to the http-interface:

    array (size=3)
      'url' => string 'http://127.0.0.1:9308/sql' (length=25)
      'headers' => 
        array (size=1)
          0 => string 'Content-Type: ' (length=14)
      'body' => string 'mode=raw&query=CALL KEYWORDS('k\xc3\xbcche*','ebiz_trader_ad_master_de')' (length=72)

And this result:

    array (size=5)
      'columns' => 
        array (size=3)
          0 => 
            array (size=1)
              'qpos' => 
                array (size=1)
                  'type' => string 'string' (length=6)
          1 => 
            array (size=1)
              'tokenized' => 
                array (size=1)
                  'type' => string 'string' (length=6)
          2 => 
            array (size=1)
              'normalized' => 
                array (size=1)
                  'type' => string 'string' (length=6)
      'data' => 
        array (size=1)
          0 => 
            array (size=3)
              'qpos' => string '1' (length=1)
              'tokenized' => string 'kxc3xbcche*' (length=11)
              'normalized' => string 'kxc3xbcche*' (length=11)
      'total' => int 0
      'error' => string '' (length=0)
      'warning' => string '' (length=0)

Currently I went to using a raw sql query like follwing to work around it, which works, but is far from ideal:

        $keywords = $this->manticoreClient()->sql([
            'mode' => 'raw',
            'body' => [
                "query" => "CALL KEYWORDS('".mysql_real_escape_string(implode("* ", $query)."*")."', '".mysql_real_escape_string($indexNameFull)."');"
            ]
        ]);

4.0.2 highlight fatal error while trying to decode JSON response

In prod we have 4.0.2 af497f2@210921 release (columnar 1.11.2 69d3780@210921)
When using highlight() we get PHP "fatal error while trying to decode JSON response".
Without highlight client returns the correct search result.
We work with the Cyrillic database and utf8mb4.

On dev we have 3.6.0 96d61d8@210504 and everything works without errors.

ScriptFields bad documentation? Кривая документация, возможно

Пытаемся сдеать по доке (try make code by query.md documentation)
https://github.com/manticoresoftware/manticoresearch-php/blob/master/docs/query.md

$bool_query = new BoolQuery();
$bool_query->must(new ScriptFields('param18',"IN(params_json['18'],106,114)") );
$bool_query->must(new Equals('param18', 1));
$results = $index->search($bool_query)->get();

Получаем ошибку (Got error) Error parsing json query: \"must\" array value should be an object

Пробуем обходной путь, но он какой-то неправильный (Other wrong way)

$bool_query = new BoolQuery();
$scriptFields = new ScriptFields();
$scriptFields->add('param18', "IN(params_json['18'],106,114)");
$bool_query->must( $scriptFields );
$bool_query->must(new Equals('param18', 1));
$results = $index->search($bool_query)->get();

Получаем ошибку (Got error) unknown column: param18

Рабочий вариант, прекрасно работает (Right Way/Work Perfect)

$search = $index->search('some text');
$search->expression('param18',"IN(params_json['18'],106,114)");
$results = $search
        ->filter('status','=',1)
        ->filter('param18','=',1)
        ->sort('publish_date','desc')
        ->limit(12)
        ->offset(0)
        ->option('ranker', null)
        ->option('max_matches',50000)
        ->get();

failed to set multiple wordforms

not quite sure how to set multiple wordform files for index

$params = [  
    'body' => [  
        'settings' => [  
             'wordforms' => '/usr/local/sphinx/data/wordforms.txt'  
        ],  
        'columns' => [  
            'title'=>['type'=>'text'],  
            'price'=>['type'=>'float']  
        ]  
    ],  
    'index' => 'products'  
];  
$index = new \Manticoresearch\Index($client);  
$index->create($params);  

however index with such config works well

index products {  
  wordforms = /usr/local/sphinx/data/wordforms.txt  
  wordforms = /usr/local/sphinx/data/alternateforms.txt  
    
  type = rt  
  path = idx  
  rt_field = title  
  rt_attr_uint = price  
}  

Bulk Upload Fails Silently

hi,

I was trying to write a bulk upload test, I went with this initially:

https://github.com/gordonbanderson/manticoresearch-php/blob/testing/test/Manticoresearch/Endpoints/BulkTest.php#L24

Now https://github.com/gordonbanderson/manticoresearch-php/blob/testing/test/Manticoresearch/Endpoints/BulkTest.php#L24 is erroneous in that a product with id of 100 already exists, an oversight on my part. However https://github.com/gordonbanderson/manticoresearch-php/blob/testing/test/Manticoresearch/Endpoints/BulkTest.php#L32 does not fail. If I add an error_log statement in src/Manticoresearch/Response.php the id duplication error shows in the response returned by the Manticore server.

I think likes of a RuntimeException should be thrown

Regards

Gordon

Feature requests: multi-attribute sorting and case-insensitive sort directions

With regard to the sort() function in the Search class, I would like to be able to specify multi-attribute sorting, like so:

$search->sort(['date' => 'DESC', 'attribute2' => 'ASC', 'attribute3' => 'DESC', 'attribute4' => 'ASC']);

It appears that the current code only allows for specifying sorting by one attribute, or by multiple attributes but all with the same sort direction.

It also appears that specifying the sort direction ('ASC' or 'DESC') as anything other than all-lowercase results in an error. It would be preferable to be able to specify these in uppercase, consistent with SQL conventions.

Inserting documents quits every time at 423908 inserts

Hi,

Rebuilding my search indexes after upgrading from 5.x to 6.x and out of 8M rows it now quits at 423908 rows. I reverted back to Manticore 5.0.2 but same issue.

Tried both PHP 8.1 and 8.2. No errors anywhere in PHP or Manticore.

I did change from using SphinxSE to using HTTP. But I do not see how that could cause this issue. Any idea?

string id turns into incorrect int

If you execute this script:

root@a25e70770258:~# cat test.php  
<?php  
require_once __DIR__ . '/vendor/autoload.php';  
  
$config = ['host'=>'127.0.0.1','port'=>9308];  
$client = new \Manticoresearch\Client($config);  
$index = $client->index('test');  
$index->drop(true);  
$index->create([]);  
$id = '1';  
$index->addDocument([], $id);  

you'll get:

root@a25e70770258:~# php test.php ; mysql -P9306 -h0 -e "select * from test"  
 ---------------------   
| id                  |  
 ---------------------   
| 5046093131288674309 |  
 ---------------------   

The expected behaviour is to convert '1' into 1 automatically.

Environment:

  • PHP 8.1.2-1ubuntu2.11
  • Ubuntu Jammy
  • Manticore 6.0.4

Unnecessary line in class Create

Method "setBody" of class "Create" has unnecessary line # 37 (of origin file /phpClient/vendor/manticoresoftware/manticoresearch-php/src/Manticoresearch/Endpoints/Indices/Create.php).

See comment inside code:

public function setBody($params = null)
{
    if (isset($this->index)) {
        $columns = [];
        if (isset($params['columns'])) {
            foreach ($params['columns'] as $name => $settings) {
                $column = $name . ' ' . $settings['type'];
                if (isset($settings['options']) && count($settings['options']) > 0) {
                    $column .= ' ' . implode(' ', $settings['options']);
                }
                $columns[] = $column;
            }
        }
        $options = "";
        if (isset($params['settings'])) {
            foreach ($params['settings'] as $name => $value) {
                $options.=" ".$name." = '".$value."'";       // ##### <----- this line is unneccessary, because the same code lower in "else" block
                if (is_array($value)) {
                    foreach ($value as $v) {
                        $options.=" ".$name." = '".$v."'";
                    }
                } else {
                    $options.=" ".$name." = '".$value."'"; // #### <----- the same code
                }
            }
        }
        return parent::setBody(['query' => "CREATE TABLE ".
            (isset($params['silent']) && $params['silent']===true?' IF NOT EXISTS ':'').
            $this->index.
            (count($columns)>0?"(".implode(",", $columns).")":" ")
            .$options]);
    }
    throw new RuntimeException('Index name is missing.');
}

URL encoding issue on equals character when passing settings to create index with Manticore 5.0

Something appears to have changed in 5.0 HTTP, if a value contains an equals sign it is expecting it to be (I assume) double encoded, I haven't checked any raw transmission logs but code that was working on 4.2 no longer works in 5.

Example:

http://x.x.x.x:9308/sql?mode=raw&query=CREATE TABLE foobar(title text) rt_mem_limit = '256M'

will fail with:

{ "error": "query missing" }

After some debug, it appears that urlencoding the options fixes the issue, and showing the index settings after reveals that the settings are applied. I'm not sure which other areas of this library are impacted by this.

The fix I have applied locally is to modify line 51 of Endpoints/Indices/Create.php to change:

.$options]);

to:

.urlencode($options)]);

How to initialize client in php without composer?

In Sphinx, I usually do it like this

    require('sphinxapi.php');
    $sp = new SphinxClient();
    $sp->SetServer('127.0.0.1',9000);
    $sp->SetArrayResult(true);
    $sp->SetMatchMode(SPH_MATCH_EXTENDED);

Now, with manticore 3.5.0, its not working anymore.

Match is a reserved word as of PHP 8.0

I stumbled upon it when I got the message: "syntax error, unexpected token "match", expecting ":"""
I have fiddled around a bit, And it seems renaming the Match object does the trick in fixing it.

addDocument() doesn't return inserted "id"

I added a document via PHP but I couldn't manage to get "id" after insert operation.

Array result;

Array
(
    [_index] => string "index_name"
    [_id] => integer 0
    [created] => boolean TRUE
    [result] => string "created"
    [status] => integer 201
)

I've checked the actual result from SphinxServer. Also, the server didn't give an "id" in the result via HTTP.

$ curl -Ss http://localhost:9312/insert -d '{"index":"index_name","doc":{"value":"ze"}}'
{"_index":"index_name","_id":0,"created":true,"result":"created","status":201}

Note: "id" has returned in the SQL.

Equals sign in search query breaks request

Greetings!

Manticore version is 5.0.2 348514c86@220530 dev (columnar 1.15.4 2fef34e@220522) (secondary 1.15.4 2fef34e@220522)

Index config:

$index->create([  
    'db_id' => ['type' => 'int'],  
    'name' => ['type' => 'text'],  
], [  
    'min_infix_len' => 2,  
    'index_exact_words' => 1,  
    'expand_keywords' => 1,  
]);  

Suppose we have in index text column with value "Product 123 name="

The following request

$result = $client->sql([  
    'body' => [  
        'query' => "SELECT * FROM products where MATCH('name=')"  
    ]  
]);  

leads to this error:

Manticoresearch\Exceptions\ResponseException  
index products: query error: syntax error, unexpected $end near  

In docs there is no information about escaping equals sign. Escaping it gives an empty result.

Metod match('word word2') generate query type AND

In documentation OR as default operator
I try profile()->match('word word2') and i see :
[query] => Array
(
[type] => AND
[description] => AND( AND( AND(KEYWORD(word, querypos=1)), AND(KEYWORD(word2, querypos=2))), OR( AND(KEYWORD(word, querypos=1)), AND(KEYWORD(word2, querypos=2))))....

if i set
->math(['query' => 'word word2', 'operator' => 'or'])
has no effect.

Possible BUG: \Manticoresearch\Search::offset() and limit() affects facet()

After playing around, I think it's a Manticore core issue, not the PHP api, so I opened an issue there

Behavior

When i use the \Manticoresearch\Search::offset() and limit() methods, it affects the resultset of the facet. I believe it is a mistake, because the SQL interface returns all the FACET rows as expected.

Reproduce

Create and fill the index

CREATE TABLE la8_test (
    title text indexed,
    description text indexed,
    str_val string,
    int_val int,
    bigint_val bigint,
    float_val float,
    bool_val bool,
    time_val timestamp,
    json_val json,
    mva_int_val multi
);
REPLACE INTO `la8_test` (id, title, description, str_val, int_val, bigint_val, float_val, bool_val, time_val, json_val, mva_int_val) VALUES (1, 'A great title 1', 'A long description 1', 'tagone', 11, 10000001, 1001.5, 1, 1634549851, '{\"a\":1,\"b\":2}', (3,5,7,9))
REPLACE INTO `la8_test` (id, title, description, str_val, int_val, bigint_val, float_val, bool_val, time_val, json_val, mva_int_val) VALUES (2, 'A great title 2', 'A long description 2', 'tagone', 12, 10000002, 1002.5, 1, 1634549850, '{\"a\":2,\"b\":3}', (4,6,8,10))
REPLACE INTO `la8_test` (id, title, description, str_val, int_val, bigint_val, float_val, bool_val, time_val, json_val, mva_int_val) VALUES (3, 'A great title 3', 'A long description 3', 'tagone', 13, 10000003, 1003.5, 1, 1634549849, '{\"a\":3,\"b\":4}', (5,7,9,11))
REPLACE INTO `la8_test` (id, title, description, str_val, int_val, bigint_val, float_val, bool_val, time_val, json_val, mva_int_val) VALUES (4, 'A great title 4', 'A long description 4', 'tagtwo', 14, 10000004, 1004.5, 1, 1634549848, '{\"a\":4,\"b\":5}', (6,8,10,12))
REPLACE INTO `la8_test` (id, title, description, str_val, int_val, bigint_val, float_val, bool_val, time_val, json_val, mva_int_val) VALUES (5, 'A great title 5', 'A long description 5', 'tagtwo', 15, 10000005, 1005.5, 1, 1634549848, '{\"a\":5,\"b\":6}', (7,9,11,13))
REPLACE INTO `la8_test` (id, title, description, str_val, int_val, bigint_val, float_val, bool_val, time_val, json_val, mva_int_val) VALUES (6, 'A great title 6', 'A long description 6', 'tagtwo', 16, 10000006, 1006.5, 1, 1634549847, '{\"a\":6,\"b\":7}', (8,10,12,14))
REPLACE INTO `la8_test` (id, title, description, str_val, int_val, bigint_val, float_val, bool_val, time_val, json_val, mva_int_val) VALUES (7, 'A great title 7', 'A long description 7', 'tagtwo', 17, 10000007, 1007.5, 1, 1634549846, '{\"a\":7,\"b\":8}', (9,11,13,15))
REPLACE INTO `la8_test` (id, title, description, str_val, int_val, bigint_val, float_val, bool_val, time_val, json_val, mva_int_val) VALUES (8, 'A great title 8', 'A long description 8', 'tagtwo', 18, 10000008, 1008.5, 1, 1634549845, '{\"a\":8,\"b\":9}', (10,12,14,16))
REPLACE INTO `la8_test` (id, title, description, str_val, int_val, bigint_val, float_val, bool_val, time_val, json_val, mva_int_val) VALUES (9, 'A great title 9', 'A long description 9', 'tagtwo', 19, 10000009, 1009.5, 1, 1634549844, '{\"a\":9,\"b\":10}', (11,13,15,17))
REPLACE INTO `la8_test` (id, title, description, str_val, int_val, bigint_val, float_val, bool_val, time_val, json_val, mva_int_val) VALUES (10, 'A great title 10', 'A long description 10', 'tagtwo', 20, 10000010, 1010.5, 1, 1634549843, '{\"a\":10,\"b\":11}', (12,14,16,18))

PHP

The ->facet('str_val') should produce 2 elements, but non is returned.
You can examine the facet result as you change the ->offset() and ->limit() values.

$client = new \Manticoresearch\Client(['host'=>'127.0.0.1','port'=>9308]);
$search = new \Manticoresearch\Search($client);

$res = $search
    ->setIndex('la8_test')
    ->search('great long description')
    ->offset(3)->limit(3) // change these to see the facet results change
    ->facet('str_val')
    ->get();

print_r($res->getResponse()->getResponse()['hits']['hits']);
print_r($res->getFacets()['str_val']['buckets']);

SQL

The same query in SQL returns the expcted 2 rows in the facet

$ mysql -h 0 -P 9306
mysql > SELECT * FROM la8_test WHERE MATCH('great long description') LIMIT 3,3 FACET str_val;
+------+---------+------------+------------+----------+--------------------+-------------+---------+-----------------+-------------+
| id   | int_val | bigint_val | time_val   | bool_val | count_optimization | float_val   | str_val | json_val        | mva_int_val |
+------+---------+------------+------------+----------+--------------------+-------------+---------+-----------------+-------------+
|    5 |      15 |   10000005 | 1634734135 |        1 |                  1 | 1005.500000 | tagtwo  | {"a":5,"b":6}   | 7,9,11,13   |
|   10 |      20 |   10000010 | 1634734130 |        1 |                  1 | 1010.500000 | tagtwo  | {"a":10,"b":11} | 12,14,16,18 |
|    9 |      19 |   10000009 | 1634734131 |        1 |                  1 | 1009.500000 | tagtwo  | {"a":9,"b":10}  | 11,13,15,17 |
+------+---------+------------+------------+----------+--------------------+-------------+---------+-----------------+-------------+
3 rows in set (0,00 sec)

+---------+----------+
| str_val | count(*) |
+---------+----------+
| tagtwo  |        7 |
| tagone  |        3 |
+---------+----------+
2 rows in set (0,00 sec)

Can i use setMachRanking?

Hello Devs
Can i use Ranking for this module? Can i use Weight for field's?

in documentation not found information

replaceDocument adds a new document and leaves the old one

I was building a wrapper around some of the provided functions and tried to use updateDocument to only find out it had an issue as stated here #10

So I switched to replaceDocument as recommended and after running it I found it only added a second document and kept the old one, not a replace.

My work around was to use the deleteDocument and then follow with a addDocument.

here is my echo/print_r output

SELECT id FROM ww_geo_zips WHERE src_id = 1    
Array    
(    
    [geo_zip_id] => 1    
    [zip] => 34051    
    [city] => FPO    
    [county] => Erie    
    [lat] => 0.716239491787173    
    [lon] => -1.9491645100054953    
    [city_zip_count] => 17    
)    
Array    
(    
    [took] => 11    
    [timed_out] =>     
    [hits] => Array    
        (    
            [total] => 1    
            [hits] => Array    
                (    
                    [0] => Array    
                        (    
                            [_id] => 6053701685393360552    
                            [_score] => 1    
                            [_source] => Array    
                                (    
                                )    
    
                        )    
    
                )    
    
        )    
    
)    
Array    
(    
    [src_id] => 1    
    [zip] => 34051    
    [city] => FPO    
    [county] => Erie    
    [lat] => 0.716239491787173    
    [lon] => -1.9491645100054953    
    [city_zip_count] => 17    
)    
RECNO: 6053701685393360552    
update    
Array    
(    
    [_index] => ww_geo_zips    
    [_id] => 0    
    [created] =>     
    [result] => updated    
    [status] => 200    
)    

Methods needed for moving from sphinxsearch to Manticore PHP API

Hello!

I'm moving from sphinxsearch and can't find several features at php api for manticore. Try to make samples with sphinx 2.0 php code.

  1. SetGroupBy method for grouping results. as far as I understand, this feature is present in manticore and maybe this feature covers by facets, but this is not covers by documentation. Please, explain - how can I group results?
  2. Set weights for fields for using custom order and ranges via SetWeights. As I read in documentation, manticore has custom weights feature via SELECT OPTIONS in SQL, but I can't find this method in php api. Not as method, not as, I don't know, some options of connection or something like that. How can I set this?

And it's not critical but - can I get primary ids from resultset as array, without array iteration? If can, how called this method?

Unix socket

Hello,

Is there any way to use unix socket connection?

Regards,

How to set match mode to SPH_MATCH_EXTENDED2 ?

Hello i am in the process of migrating to manticore from an old sphinx installation but i cannot find any options on how to set match mode to SPH_MATCH_EXTENDED2, is it not supported?

Here is part of the old code for reference

    $sphinx = new SphinxClient;
    $sphinx->SetServer('localhost', 9312);
    $sphinx->SetMatchMode(SPH_MATCH_EXTENDED2);
    $sphinx->SetRankingMode(SPH_RANK_EXPR,'sum((4*lcs+2*(min_hit_pos==1)+exact_hit)*user_weight)*1000 + IF(IN(f1, "1"), 0, 10000) + IF(IN(f2, "1"), 0, 10000) + bm25');
    $sphinx->SetFieldWeights(['email' => 0]);
    $sphinx->Query($s, 'index0')['matches'];

Parts of raw SQL response get lost

To reproduce:

<?php
require_once __DIR__ . '/vendor/autoload.php';
$config = ['host' => '127.0.0.1', 'port' => 9308];
$client = new \Manticoresearch\Client($config);

$index = new \Manticoresearch\Index($client);
$index->setName('test');
$index->create(
    ['word' => ['type' => 'text']],
    [
        'min_infix_len' => '3',
        'index_exact_words' => '1',
        'expand_keywords' => '1',
        'bigram_index' => 'all'
    ],
);

$index->addDocuments([['id' => 1, 'word' => 'one two three'], ['id' => 2, 'word' => 'one five seven'], ['id' => 3, 'word' => 'zero one six']]);

$query = "CALL KEYWORDS('on*', 'test', 1 as stats, 'hits' as sort_mode);";
$params = ['mode' => 'raw', 'body' => ['query' => $query]];

print_r($client->sql($params));

That will deliver the last result and lose the rest, something like that:

Array
(
    [1] => Array
        (
            [tokenized] => on*
            [normalized] => one two
            [docs] => 1
            [hits] => 1
        )

)

The underlying response would have all the data though:

array(5) {
  ["columns"]=>
  array(5) {
    [0]=>
    array(1) {
      ["qpos"]=>
      array(1) {
        ["type"]=>
        string(6) "string"
      }
    }
    [1]=>
    array(1) {
      ["tokenized"]=>
      array(1) {
        ["type"]=>
        string(6) "string"
      }
    }
    [2]=>
    array(1) {
      ["normalized"]=>
      array(1) {
        ["type"]=>
        string(6) "string"
      }
    }
    [3]=>
    array(1) {
      ["docs"]=>
      array(1) {
        ["type"]=>
        string(6) "string"
      }
    }
    [4]=>
    array(1) {
      ["hits"]=>
      array(1) {
        ["type"]=>
        string(6) "string"
      }
    }
  }
  ["data"]=>
  array(4) {
    [0]=>
    array(5) {
      ["qpos"]=>
      string(1) "1"
      ["tokenized"]=>
      string(3) "on*"
      ["normalized"]=>
      string(3) "one"
      ["docs"]=>
      string(1) "3"
      ["hits"]=>
      string(1) "3"
    }
    [1]=>
    array(5) {
      ["qpos"]=>
      string(1) "1"
      ["tokenized"]=>
      string(3) "on*"
      ["normalized"]=>
      string(8) "one five"
      ["docs"]=>
      string(1) "1"
      ["hits"]=>
      string(1) "1"
    }
    [2]=>
    array(5) {
      ["qpos"]=>
      string(1) "1"
      ["tokenized"]=>
      string(3) "on*"
      ["normalized"]=>
      string(7) "one six"
      ["docs"]=>
      string(1) "1"
      ["hits"]=>
      string(1) "1"
    }
    [3]=>
    array(5) {
      ["qpos"]=>
      string(1) "1"
      ["tokenized"]=>
      string(3) "on*"
      ["normalized"]=>
      string(7) "one two"
      ["docs"]=>
      string(1) "1"
      ["hits"]=>
      string(1) "1"
    }
  }
  ["total"]=>
  int(0)
  ["error"]=>
  string(0) ""
  ["warning"]=>
  string(0) ""
}

It seems that the SqlToArray class makes too many assumptions about the structure of the input data and in case of the above response this line

$data[array_shift($property)] = $property;
will keep overwriting the relevant part of data so only the last result remains.

use rt_field directive

I have a script that I use to make a number of rt indexes which works fine like this.

'ww_blocked_ips' => [
	'src_id'        => ['type' => 'bigint'],
	'ip' 			=> ['type' => 'text'],
	'reason'		=> ['type' => 'uint'],
	'user_id'		=> ['type' => 'uint'],
	'creation_time'	=> ['type' => 'uint']
],

my code changes this as need for manticoresearch-php to make a index.
The issue is here

'ww_business_names' => [
    'src_id'    	=> ['type' => 'uint'],
    'name'          => ['type' => 'string'],
    'city'          => ['type' => 'string'],
    'state'         => ['type' => 'uint'],
    'featured'      => ['type' => 'uint'],
    'seo_url'       => ['type' => 'string']
],

The response I get is ...

PHP Fatal error:  Uncaught Manticoresearch\Exceptions\ResponseException: "error adding index 'ww_business_names': no fields configured (use rt_field directive)" in /var/www/html/manticore/vendor/manticoresoftware/manticoresearch-php/src/Manticoresearch/Transport/Http.php:126
Stack trace:
#0 /var/www/html/manticore/vendor/manticoresoftware/manticoresearch-php/src/Manticoresearch/Client.php(353): Manticoresearch\Transport\Http->execute()
#1 /var/www/html/manticore/vendor/manticoresoftware/manticoresearch-php/src/Manticoresearch/Indices.php(74): Manticoresearch\Client->request()
#2 /var/www/html/manticore/vendor/manticoresoftware/manticoresearch-php/src/Manticoresearch/Index.php(239): Manticoresearch\Indices->create()
#3 /var/www/html/manticore/manticore.php(60): Manticoresearch\Index->create()
#4 /var/www/html/manticore/manticore.php(287): viath\manticore\manticore->create_indexes()
#5 {main}
  thrown in /var/www/html/manticore/vendor/manticoresoftware/manticoresearch-php/src/Manticoresearch/Transport/Http.php on line 126

any ideas?

Connection pool is not reset when no more retries left

If a query reaches the no more retries left, another query following the first one will not try any connection, because the pool doesn't do a reset on retries attempts or unmarking the connections.
This is a problem if the client is used in a scenario where is expected to have failures on a query but continue the script execution.

Mva properties are updated via API /json

manticore version:3.3.0 01fc8ad@200204 release

$client = new client(); $data = [ 'body' => [ 'index' => 'indexname', 'id' =>100, 'doc' => [ 'rent' => '(1,2)', 'gid' => 26, ] ] ]; $client->update($data)

return:
{"error":{"type":"index indexname: attribute 'rent' MVA flag mismatch","index":"indexname"},"status":500}

How should I write the rent value of mva property?
I tried the following ways:
1: 'doc'=>[ 'rent' => [1,2,3] ]
2: 'doc'=>[ 'rent' => '(1,2,3)' ]
3: 'doc'=>[ 'rent' => '[1,2,3]' ]
4: 'doc'=>[ 'rent' => jsone_ncode([1,2,3]) ]
Return the error message above
I'm freaking out. I don't know what to do
help me
thanks

Error on JSON decode after keywords request ("\x03" symbol)

Hello! First of all, thanks for the awesome tool and great job to all of the Manticoresearch team !

Below's my index settings:

$index->create([
    'db_id' => ['type' => 'int'],
    'name_full' => ['type' => 'text'],
], [
    'morphology' => '',
    'bigram_index' => 'all',
    'min_infix_len' => 2,
    'index_exact_words' => 1,
    'expand_keywords' => 1,
]);

$id = 1;
$name_full = "Some long product name...";

$index->addDocument([
    'db_id' => (int) $id,
    'name_full' => (string) $name_full,
]);

$keywords = $client->keywords([
    'index' => $indexName,
    'body' => [
        'query' => "$term*",
        'options' => ['stats' => 1, 'sort_mode' => "'hits'"]
    ]
]);

After request on keywords I got this error:

Manticoresearch\Exceptions\RuntimeException: fatal error while trying to decode JSON response in /app/vendor/manticoresoftware/manticoresearch-php/src/Manticoresearch/Response.php:76
Stack trace:
#0 /app/vendor/manticoresoftware/manticoresearch-php/src/Manticoresearch/Response/SqlToArray.php(11): Manticoresearch\Response->getResponse()
#1 /app/vendor/manticoresoftware/manticoresearch-php/src/Manticoresearch/Response.php(92): Manticoresearch\Response\SqlToArray->getResponse()
#2 /app/vendor/manticoresoftware/manticoresearch-php/src/Manticoresearch/Transport/Http.php(124): Manticoresearch\Response->hasError()
#3 /app/vendor/manticoresoftware/manticoresearch-php/src/Manticoresearch/Client.php(353): Manticoresearch\Transport\Http->execute()
#4 /app/vendor/manticoresoftware/manticoresearch-php/src/Manticoresearch/Client.php(325): Manticoresearch\Client->request()
#5 /app/backend/controllers/TestController.php(591): Manticoresearch\Client->keywords()

Here's the raw response result:

{"columns":[{"qpos":{"type":"string"}},{"tokenized":{"type":"string"}},{"normalized":{"type":"string"}},{"docs":{"type":"string"}},{"hits":{"type":"string"}}],\
"data":[\n
{"qpos":"1", "tokenized":"принт*", "normalized":"=принтер", "docs":"1148", "hits":"1153"},\n
{"qpos":"1", "tokenized":"принт*", "normalized":"=принтер\x03этикеток", "docs":"404", "hits":"404"},\n
{"qpos":"1", "tokenized":"принт*", "normalized":"=принтера", "docs":"25", "hits":"25"},\n
{"qpos":"1", "tokenized":"принт*", "normalized":"=принтера\x03aura", "docs":"13", "hits":"13"},\n
{"qpos":"1", "tokenized":"принт*", "normalized":"=принтер\x03canon", "docs":"7", "hits":"7"},\n
{"qpos":"1", "tokenized":"принт*", "normalized":"=принтер\x03hp", "docs":"5", "hits":"5"},\n
{"qpos":"1", "tokenized":"принт*", "normalized":"=принтер\x03xerox", "docs":"5", "hits":"5"},\n
{"qpos":"1", "tokenized":"принт*", "normalized":"=принтер\x03epson", "docs":"3", "hits":"3"},\n
{"qpos":"1", "tokenized":"принт*", "normalized":"=принтера\x03tdp", "docs":"3", "hits":"3"},\n
{"qpos":"1", "tokenized":"принт*", "normalized":"=принтера\x03tsc", "docs":"3", "hits":"3"},\n
{"qpos":"1", "tokenized":"принт*", "normalized":"=принтеров", "docs":"3", "hits":"3"},\n
{"qpos":"1", "tokenized":"принт*", "normalized":"=принтер\x03kyocera", "docs":"2", "hits":"2"},\n
{"qpos":"1", "tokenized":"принт*", "normalized":"=принтера\x03pp", "docs":"2", "hits":"2"},\n
{"qpos":"1", "tokenized":"принт*", "normalized":"=принтера\x03tтp", "docs":"2", "hits":"2"},\n
],\n
"total":0,\n
"error":"",\n
"warning":""\n
}

It seems that issue is related to "\x03" symbol. For some reason, Manticore puts it instead of whitespace.

Coding Standards Compliance

hi Adrian,

Firstly I do not with to add a PR for this as my stats would be unfairly over the codebase. However I normally use phpcs and phpcbf to detect and fix errors against the PSR2 coding standard.

Locally I have ran these commands

  1. Automated adherence to coding standards
vendor/bin/phpcbf --standard=PSR2 src/ test/

This alters source code so please ensure that it is backed up prior to running these commands.

  1. Whilst one of the Travis tasks I added checks for coding standards, I have set it to not fail. If the above command is run over the codebase, then the PHP_CS task in Travis can be set to this, which will fail the build if coding standards are not adhered to.
vendor/bin/phpcs --standard=PSR2 src/ test/

Running locally the warnings the command is picking up mostly long lines, and also tests with missing namespaces. For example:

FILE: /var/www/html/manticoresearch-php/test/Manticoresearch/Endpoints/SearchTest.php
-----------------------------------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
-----------------------------------------------------------------------------------------------
 6 | ERROR | Each class must be in a namespace of at least one level (a top-level vendor name)
-----------------------------------------------------------------------------------------------

In my professional experience using phpcs and phpcbf is a good thing to do.

Cheers

Gordon

Unable to Create Cluster

hi Adrian,

I am trying to get clusters working with Travis, but have run into a problem in trying to create a cluster.

The relevant code is here, https://github.com/gordonbanderson/manticoresearch-php/blob/CLUSTER/test/ClusterTest.php

The output of a relevant Travis job, https://travis-ci.org/github/gordonbanderson/manticoresearch-php/jobs/682702724#L454, and indicates an error thus:

only SELECT queries are supported

I cannot find this in the manticore search PHP code, so I can only assume this is being returned by the Manticoresearch server?

Cheers

Gordon

Undefined array key "took"

Getting these seemingly randomly. Any ideas?

  Undefined array key "took"      
      
  at vendor/manticoresoftware/manticoresearch-php/src/Manticoresearch/ResultSet.php:48      
     44▕             $this->total = $response['hits']['total'];      
     45▕         } else {      
     46▕             $this->total = 0;      
     47▕         }      
  ➜  48▕         $this->took = $response['took'];      
     49▕         $this->timed_out = $response['timed_out'];      
     50▕         if (isset($response['profile'])) {      
     51▕             $this->profile = $response['profile'];      
     52▕         }      
      
       2 vendor frames      

Update Failing With Unknown Attribute Error

hi,

Trying to write an update test, updating the only product with id 100.

https://github.com/gordonbanderson/manticoresearch-php/blob/testing/test/Manticoresearch/Endpoints/UpdateTest.php#L42

The error I get is

1) Manticoresearch\Test\Endpoints\UpdateTest::testUpdateProduct
Manticoresearch\Exceptions\ResponseException: {"type":"index products: attribute 'title' not found","index":"products"}

/var/www/html/manticoresearch-php/src/Manticoresearch/Transport/Http.php:123
/var/www/html/manticoresearch-php/src/Manticoresearch/Client.php:322
/var/www/html/manticoresearch-php/src/Manticoresearch/Client.php:208
/var/www/html/manticoresearch-php/test/Manticoresearch/Endpoints/UpdateTest.php:56

If I call describe endpoint prior to running this test I can see id, title and price. Does attribute mean a column here?

Or if I have made a mistake please let me know. But from the documentation I think my approach is correct.

Regards

Gordon

Creating a new client with fully qualified strategy class name takes too long

Slow:

		$client = new \Manticoresearch\Client([  
			'connections' => $config_connections,  
			'connectionStrategy' => \Manticoresearch\Connection\Strategy\StaticRoundRobin::class,  
			'retries' => 3  
		]);  

Fast:

		$client = new \Manticoresearch\Client([  
			'connections' => $config_connections,  
			'connectionStrategy' => 'StaticRoundRobin',  
			'retries' => 3  
		]);  

Creating a new client with fully qualified strategy class name takes too long (up to 100ms) because it assumes that we pass a short class name for \\Manticoresearch\\Connection\\Strategy\\ namespace.

Slowdown comes from the method class_exists('\\Manticoresearch\\Connection\\Strategy\\' . $this->config['connectionStrategy']).

The second argument of the method class_exists is set to true by default and it calls autoloader.

Solution could be to set the second parameter of class_exists call to false, or remove class_exists call and assume that class always exist.

Indices/Alter.php not working as expected

Using Indices/Alter.php to add a column to an index failes with

sphinxql: syntax error, unexpected $undefined, expecting CLUSTER or RTINDEX or TABLE near '+TABLE+test+ADD+COLUMN+benefits+JSON'"

If I understand the manticore API documentation correctly, that is expected, because Alter.php extends EmulateBySql.php and that enforces mode=raw, but the docs state that

you can set HTTP parameter mode to raw , and then the rest of the query after 'query=' will be passed inside without any substitutions/url decoding

So if I'm not mistaken, either the urlencode in Sql.php must be skipped if $k==='query', or I'm at a loss at what is supposed to happen, where my misconception lies (Edit: or this is very much a work-in-progress and I should refrain from checking out master if a perfectly good release is there)

In keywords() and suggest() methods, there is no way to pass a word with a single quote

<?php    
require_once __DIR__ . '/vendor/autoload.php';    
use Manticoresearch\Utils;    
    
$config = ['host'=>'127.0.0.1','port'=>9308];    
$client = new \Manticoresearch\Client($config);    
$index = $client->index('t');    
    
$params = [    
   'index' => 't',    
   'body' => ['silent'=>true ]    
];    
$client->indices()->drop($params);    
    
$index->create([    
    'f'=>['type'=>'text']    
], [    
    //'blend_chars' => "'"    
    'blend_chars' => 'U 27'    
]);    
    
$index->addDocuments([    
        ['id'=>1,'f'=>"abc'def"],    
    ]);    
    
$results = $index->search("abc'def")->get();  //Ok    
$words = $index->keywords("abc\'def", []);  //sphinxql: syntax error, unexpected identifier, expecting ')' near 'def'    
    
print_r($results);    
print_r($words);    

Here is a working variant if using the method client->sql()

$params = [    
    'mode' => 'raw',    
    'body' => [    
        'query' => "CALL KEYWORDS('abc\'def', 't', 1 as stats, 1 as fold_blended)"    
    ]    
];    
    
$words = $this->client->sql($params);    

fix cluster test instability

There's a workaround in https://github.com/manticoresoftware/manticoresearch-php/blob/master/test/Manticoresearch/ClusterTest.php#L103 :

        // workaround against unstable tests. For some reason the replication which
        // has to be synchronous acts like if it was asynchronous
        sleep(3);

without it it has a high chance to fail which looks wrong since given Manticore has synchronous replication it should be stable without the sleep(N). The task is to figure out what's going on and create another issue in https://github.com/manticoresoftware/manticoresearch/ if the problem is on that end.

suggest не работает

$config = ['host'=>'manticore','port'=>9308]  
$client = new Client($config);  
$suggest = $client->index('suggest');  
$suggest->create([  
            'explanation' => [  
                'type' => 'text',  
            ],  
        ],  
        [  
            'min_infix_len' => 1,  
            'dict' => 'keywords',  
        ]);  
  
$suggest->addDocument([  
                'explanation' => 'Автобус',  
            ]);  

затем:

$query = [  
        'index' => 'suggest',  
        'body' => [  
            'query' => 'овтобус',  
            'options' => [  
                'limit' => 1,  
            ],  
        ],  
    ];  
      
$r = $client->suggest($query);  

Результат пустой

Incorrect Documentation On Bulk Upload

This one is fairly minor, but it caused me a bit of head scratching until I noticed the documentation on the home README.md page.

At https://github.com/manticoresoftware/manticoresearch-php/blob/master/docs/usage.md#bulk the insert, update and delete directives are not enclosed in square brackets (there is a layer of []) missing.

$doc = [
    'body' => [
        'insert' => [
            'index' => 'testrt',
            'id' => 34,
            'doc' => [
                'gid' => 1,
                'title' => 'a new added document',
            ]
        ],
        'update' => [
            'index' => 'testrt',
            'id' => 56,
            'doc' => [
                'gid' => 4,
            ]
        ],
        'delete' => [
            'index' => 'testrt',
            'id' => 100
        ]
    ]
];

Multiple application of insert only adds one document, as there are multiple array keys for insert. I think it should be this:

$doc = [
    'body' => [
       [ 'insert' => [
            'index' => 'testrt',
            'id' => 34,
            'doc' => [
                'gid' => 1,
                'title' => 'a new added document',
            ]
        ]],
        ['update' => [
            'index' => 'testrt',
            'id' => 56,
            'doc' => [
                'gid' => 4,
            ]
        ]],
        ['delete' => [
            'index' => 'testrt',
            'id' => 100
        ]]
    ]
];

The repository README.md has this, which works, and the discrepancy appears to be the missing array brackets to denote an array of arrays.

    $docs =[
      ['insert'=> ['index'=>'movies','id'=>2,'doc'=>['title'=>'Interstellar','plot'=>'A team of explorers travel through a wormhole in space in an attempt to ensure humanity\'s survival.','year'=>2014,'rating'=>8.5]]],
      ['insert'=> ['index'=>'movies','id'=>3,'doc'=>['title'=>'Inception','plot'=>'A thief who steals corporate secrets through the use of dream-sharing technology is given the inverse task of planting an idea into the mind of a C.E.O.','year'=>2010,'rating'=>8.8]]],
      ['insert'=> ['index'=>'movies','id'=>4,'doc'=>['title'=>'1917 ','plot'=>' As a regiment assembles to wage war deep in enemy territory, two soldiers are assigned to race against time and deliver a message that will stop 1,600 men from walking straight into a deadly trap.','year'=>2018,'rating'=>8.4]]],
      ['insert'=> ['index'=>'movies','id'=>5,'doc'=>['title'=>'Alien','plot'=>' After a space merchant vessel receives an unknown transmission as a distress call, one of the team\'s member is attacked by a mysterious life form and they soon realize that its life cycle has merely begun.','year'=>1979,'rating'=>8.4]]]
    ];
    $client->bulk(['body'=>$docs]);

Including distance value in search results

Hi Adrian,

I'm not sure if I should be asking this here but thanks in advance!

The distance value of a GEODIST query is not included in the results, can you tell me if this is at all possible using the JSON API or will I have to use SQL to achieve this? e.g. I can do this via SQL

SELECT *, GEODIST(50.724789, -3.531281, latitude, longitude, {in=deg, out=km}) AS distance FROM myindex

It's not often I need to display the distance but it would be nice if at all possible to not have to post process the results to recalculate it

My usage:

        $searchQuery = new \Manticoresearch\Query\BoolQuery();
        $searchQuery->must(new \Manticoresearch\Query\Distance([
                            'location_anchor'=>
                                ['lat'=>floatval($latitude), 'lon'=> floatval($longitude)],
                            'location_source' => ['latitude', 'longitude'],
                            'location_distance' => '75 mi'
                        ]));
        $search = $index->search($searchQuery);
        $search->sort([
            '_geo_distance' =>[
                'location_anchor'=>
                    ['lat'=>floatval($latitude), 'lon'=> floatval($longitude)],
                'location_source' => [
                    'latitude',
                    'longitude'
                ],
                'order' => 'desc'
            ]
        ]);
        $result = $search->limit($limit)->get();

Allow to user filter with BOOL condition

Hi.

Quite often there is a need to use filters with an OR condition.

At the moment, this feature is available when using queries, but not when using filters.

$bool2 = new \Manticoresearch\Query\BoolQuery();
$bool2->should(new \Manticoresearch\Query('year', 2000));
$bool2->should(new \Manticoresearch\Query('year', 2010));
$bool->must($bool2);

it will be great if you can integrate this feature into this awesome project.
Thank you

Set Field Weights

Здравствуйте. Никак не могу разобраться как при помощи данного клиента можно задать приоритет полям


$client = new \Manticoresearch\Client( array(
	'host' => $config_db['manticore.db_server'],
	'port' => 9308) 
);

$this->manticore = new \Manticoresearch\Search($client);

$this->manticore->setIndex('index');

$this->manticore->maxMatches($config->maxResults);
$this->manticore->limit(30);

if (isset($filter['visible']))
	$this->manticore->filter('visible', 'eq', intval($filter['visible']));

// только для продуктов так как нужный индекс есть только там
if (!empty($filter['status']))
	$this->manticore->filter('status', 'in', (array) $filter['status']);


// только для продуктов так как нужный индекс есть только там
if (!empty($filter['sort_priority_stock']))
	$this->manticore->sort('status_sort', 'desc');


$result_search] = array();
$results = $this->manticore->match(['query'=>$search_query, 'operator'=>'and'])->get();

foreach($results as $hit)
{
	$result_search[] = $hit->getId();
}

Add a method to get total facets count

The library doesn't have a method to get total count of facets.

Here is the code example, imagine an index jobs with columns employer_id and employer_name:

$client = new \Manticoresearch\Client();
$index = $client->index('jobs');

$query = new \Manticoresearch\Query\BoolQuery();
$query->must(new \Manticoresearch\Query\MatchQuery('amazon', 'employer_name'));

$search = $index->search($query);
$search->limit(0);
$search->offset($offset);
$search->facet('employer_id', null, $per_page);
$result = $search->get();

var_dump($result->getTotal()); // this returns total number of rows, not total number of facets
var_dump($result->getFacets()); // this returns facets

So, adding a method similar to this one could solve the issue:

$result->getTotalFacets()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.