在 CouchDB Doctrine Symfony 2 中使用 Like%

Use Like% in CouchDB Doctrine Symfony 2

我正在使用这个 bundle 我想通过 %LIKE% mysql

找到我的元素

我的文档是这样的:

{
   "_id": "60a403542a2b7d44bf84ed569d1e6efe",
   "_rev": "1-9e1ed380dd91ac8c835ef0f8e152f0a8",
   "type": "mytype",
   "doctrine_metadata": {
       "indexes": [
           "name",
       ]
   },
   "name": "barfoo",

}

我想查找所有以 barfo

开头的元素

我看到了这个 link,但我不知道这是否是正确的解决方案。 我如何在 couchDb + symfony2 中进行 Like 查询?

couchDb (1.6.1) 中没有 %Like%,但您可以使用 startkey 和 endkey。

您必须创建如下视图:

function (doc) {
    if (doc.type = 'myType') {
        emit(doc.name, doc.name);
    }
}

名称例如 people

例如和简单

Designname = people
viewname = people

之后你可以做这个卷曲

curl -X GET 'http://localhost:5984/db/_design/people/_view/people?startkey="foo"&endkey="foo\ufff0"'

这样你就可以找到所有以foo开头的元素。

为什么是 \ufff0 ?检查这个 link

String Ranges

If you need start and end keys that encompass every string with a given prefix, it is better to use a high value unicode character, than to use a 'ZZZZ' suffix.

That is, rather than:

startkey="abc"&endkey="abcZZZZZZZZZ" You should use:

startkey="abc"&endkey="abc\ufff0"

你如何在 Symfony 中做到这一点?

如果你想通过 Symfony 创建视图 您可以在 yourapp/AppBundle/CouchDocument/View/PeopleView.php

中创建视图
<?php

namespace yourapp\AppBundle\CouchDocument\View;

use Doctrine\CouchDB\View\DesignDocument;

class PeopleView implements DesignDocument
{

    public function getData()
    {
        $people = <<<'JS'
function (doc) {
        if (doc.type = 'myType') {
            emit(doc.name, doc.name);
        }
    }
JS;

        return array(
            'views' => array(
                'people' => array(
                    'map' => $people,
                ),
            )
        );

    }
}

在你的控制器中你可以做这样的事情

/**
 * @Route("/testPeople/{code}", name="test_people")
 * @Method({"GET"})
 * @Template("myAppBundle:People:test_query.html.twig")
 */
public function testPeopleAction($code)
{

    $dm = $this->container->get(
        'doctrine_couchdb.odm.default_document_manager'
    );
    $peopleView = new PeopleView();
    $client = $this->container->get('doctrine_couchdb.odm.default_document_manager');
    $view = $client->createDesignDocument('people', $peopleView);

    $relatedObjects = $dm->createNativeQuery('people', 'people')
        ->setStartKey($code)
        ->setEndKey($code . "\xEF\xBF\xB0")
        ->execute();
    $a = array();
    foreach ($relatedObjects as $doc) {
        $a[] = $doc['value'] //it is your results
    }

    return array(
        'results' => $a
    );
}

我看到里面的unitTest vendor/doctrine/couchdb/tests/Doctrine/Tests/CouchDB/CouchDBClientTest.php 找到有用的东西

我不知道这是否是最好的方法,但对我来说它有效:)