loilo / Fuse

🔍 Fuzzy search for PHP, ported from Fuse.js
Apache License 2.0
322 stars 30 forks source link

`limit` option does not work #126

Closed bounlu closed 11 months ago

bounlu commented 11 months ago

No matter what limit is specified, the results array return all the items. Basically limit option is not taken into effect.

$list = [
    [
        'title' => "Old Man's War",
        'author' => 'John Scalzi',
    ],
    [
        'title' => 'The Lock Artist',
        'author' => 'Steve Hamilton',
    ],
    [
        'title' => 'HTML5',
        'author' => 'Remy Sharp',
    ],
    [
        'title' => 'Right Ho Jeeves',
        'author' => 'P.D Woodhouse',
    ],
];

$options = [
    'keys' => ['author'],
    'limit' => 1,
];

$fuse = new \Fuse\Fuse($list, $options);

echo "<pre>";
print_r($fuse->search('o'));
echo "</pre>";

$list = [
    [
        'title' => "Old Man's War",
        'author' => 'John Scalzi',
    ],
    [
        'title' => 'The Lock Artist',
        'author' => 'Steve Hamilton',
    ],
    [
        'title' => 'HTML5',
        'author' => 'Remy Sharp',
    ],
    [
        'title' => 'Right Ho Jeeves',
        'author' => 'P.D Woodhouse',
    ],
];

$options = [
    'keys' => ['author'],
    'limit' => 2,
];

$fuse = new \Fuse\Fuse($list, $options);

echo "<pre>";
print_r($fuse->search('o'));
echo "</pre>";

Both examples above return the same result:

Array
(
    [0] => Array
        (
            [item] => Array
                (
                    [title] => Old Man's War
                    [author] => John Scalzi
                )

            [refIndex] => 0
        )

    [1] => Array
        (
            [item] => Array
                (
                    [title] => Right Ho Jeeves
                    [author] => P.D Woodhouse
                )

            [refIndex] => 3
        )

    [2] => Array
        (
            [item] => Array
                (
                    [title] => The Lock Artist
                    [author] => Steve Hamilton
                )

            [refIndex] => 1
        )

)

Is this a bug or am I missing something?

loilo commented 11 months ago

Hey @bounlu.

Yes, you've missed out on a minor detail. (No worries, somebody else already did before as well.)

The limit option is not part of the new Fuse(...) options but of the options to the search method. (More precisely: It's the only option of the search method as of now).

So what you'd want to do is this:

$options = [
    'keys' => ['author'],
-    'limit' => 1,
];

$fuse = new \Fuse\Fuse($list, $options);

echo "<pre>";
-print_r($fuse->search('o'));
+print_r($fuse->search('o', [ 'limit' => 1 ]));
echo "</pre>";

Hope this helps. :)

bounlu commented 11 months ago

I see, thanks for the quick response. It works fine that way.