Code Monkey home page Code Monkey logo

search-bundle's Introduction

Algolia for Symfony

The perfect starting point to integrate Algolia within your Symfony project

CircleCI Total Downloads Latest Version License

DocumentationPHPLaravelCommunity ForumStack OverflowReport a bugFAQSupport

✨ Features

  • Simple: You can get started with only 5 lines of YAML
  • Robust: It benefits from all the new features of our PHP Client v2, like the wait() method
  • Flexible: All methods take optional $requestOptions to let you handle your data as you wish
  • Dev-friendly: Auto-completion and type-hinting thanks to an exhaustive documentation

Algolia SearchBundle supports PHP > 7.1

💡 Getting Started

First, install Algolia Search Bundle Integration via the composer package manager:

composer require algolia/search-bundle

You will also need to provide the Algolia App ID and Admin API key. By default, they are loaded from environment variables ALGOLIA_APP_ID and ALGOLIA_API_KEY.

If you use .env config file, you can set them there.

ALGOLIA_APP_ID=XXXXXXXXXX
ALGOLIA_API_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

If you don't use environment variables, you can set them in your parameters.yml.

parameters:
    env(ALGOLIA_APP_ID): XXXXXXXXXX
    env(ALGOLIA_API_KEY): xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Indexing data

First, we need to define which entities should be indexed in Algolia. Each entry under the indices config key must contain at least the 2 following attributes:

  • name is the canonical name of the index in Algolia
  • class is the full name of the entity to index

Example:

algolia_search:
  indices:
    - name: posts
      class: App\Entity\Post

Via CLI

Once your indices config is ready, you can use the built-in console command to batch import all existing data.

# Import all indices
php bin/console search:import

# Choose what indices to reindex by passing the index name
php bin/console search:import --indices=posts,comments

Before re-indexing everything, you may want to clear the index first, see how to remove data.

Simple Search

In this example we'll search for posts. The search method will query Algolia to get matching results and then will create a doctrine collection. The data are pulled from the database (that's why you need to pass the Doctrine Manager).

$em = $this->getDoctrine()->getManagerForClass(Post::class);

$posts = $this->searchService->search($em, Post::class, 'query');

For full documentation, visit the Algolia Symfony Search Bundle.

Troubleshooting

Encountering an issue? Before reaching out to support, we recommend heading to our FAQ where you will find answers for the most common issues and gotchas with the bundle.

Use the Dockerfile

If you want to contribute to this project without installing all its dependencies, you can use our Docker image. Please check our dedicated guide to learn more.

📄 License

Algolia Symfony Search Bundle is an open-sourced software licensed under the MIT license.

search-bundle's People

Contributors

alcaeus avatar alex-ception avatar algoliareadmebot avatar beamop avatar brunonic avatar chloelbn avatar chrjean avatar devincodes avatar djfm avatar gregquat avatar guillaume-ro-fr avatar iliyazelenko avatar jesko-plitt avatar julienbourdeau avatar kgonella avatar kiler129 avatar maciekpaprocki avatar matts2cant avatar maxiloc avatar mpclarkson avatar nunomaduro avatar ogizanagi avatar ostrolucky avatar piotrplenik avatar rayrutjes avatar redox avatar romainnorberg avatar sarahdayan avatar tomklotzpro avatar tristanbes 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  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

search-bundle's Issues

Index name prefix problem in config.yml

I set up the bundle as mentionned in the documentation (Fill in your Algolia credentials) :

# Algolia
algolia:
    catch_log_exceptions: true
    index_name_prefix: staging

And i get this error :

  [Symfony\Component\Config\Definition\Exception\InvalidConfigurationException]
  Unrecognized option "index_name_prefix" under "algolia"

algolia:reindex error : A slave index is already slave of another index

Hi,

When I reindex my entity with the command php bin/console algolia:reindex BecowoMemberBundle:Membe I get the error

[AlgoliaSearch\AlgoliaException]
A slave index is already slave of another index

I found a solution but it's heavy !
I delete the replica of my index in the dashboard
Then reindex my entity
Then redo the replica in the dashboard

Any help ?
Thanks

Missing entries during a reindex

Hello guys,

I am having trouble with algolia while reindexing an entity. There are some entries missing !

Here is my IndexIf:

     /**
     * @Algolia\IndexIf
     * @return boolean
     */
    public function isAlgolia()
    {
        return $this->published && $this->occuringDate > new \DateTime();
    }

And here is my database state:

SELECT DISTINCT count(*) FROM event WHERE occuring_date > NOW() AND published = true ;
 count 
-------
  2561
(1 row)

And I have 1687 records on my algolia dashboard.

Now the reindex command used to work on smaller amounts of entries, but since we made a x3 it seems some are missing. Event stranger, if I make any operations on a missing entity, it appears back in the indexes, so The IndexIf doesn't seem to be the matter.

I run a free plan, so I wonder if this could have any link ?

I will update this issue if I find a pattern between the events that are missing as currently it seems to be completely random.

Timeout config

Hello,

Since our new hoster installed a dedicated firewall (stormpath), the algolia request is taking at least 6 seconds to accomplish (i don't know why)

Can you expose a global settings in the bundle to increase the timeout option of the php library undearneath please ( http://stackoverflow.com/questions/35693340/algolia-php-sdk-hosts-unreachable
) ?

Uncaught PHP Exception AlgoliaSearch\AlgoliaException: 
"Hosts unreachable: Resolving timed out after 2000 milliseconds,Resolving timed out after 2000 milliseconds,Resolving timed out after 4000 milliseconds,Resolving timed out after 4000 milliseconds" 
at vendor/algolia/algoliasearch-client-php/src/AlgoliaSearch/Client.php line 440 {"exception":"[object] (AlgoliaSearch\\AlgoliaException(code: 0): Hosts unreachable: Resolving timed out after 2000 milliseconds,Resolving timed out after 2000 milliseconds,Resolving timed out after 4000 milliseconds,Resolving timed out after 4000 milliseconds at //vendor/algolia/algoliasearch-client-php/src/AlgoliaSearch/Client.php:440)"} []

Slaves config : facets on a slave indice

Hi,

I'm trying to understand how I can set facets on a slave indice. I have annotations like this:

/**
 * Event
 *
 * @ORM\Table(name="event")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\EventRepository")
 * @ORM\HasLifecycleCallbacks
 * @Serializer\ExclusionPolicy("all")
 * @AppAssert\HasMorePlacesThanBookings()
 * @Algolia\Index(
 *     attributesForFaceting = {"macroCategoryTitle", "timeStamp"},
 *     ranking = {"asc(timeStamp)", "typo","geo","words","filters","proximity","attribute","exact","custom"},
 *     customRanking = {"asc(finalPrice)"},
 *     slaves = {"Event_dev_final_price_asc"}
 * )
 */
class Event

The problem is that the slave that created does not have the same attributesForFaceting when I push the configuration so when I sort my results my facets widgets disapear 😢

Any idea how to make this work ?

Cheers

Serialize linked entity before indexing to algolia

Hello everyone,

I have a tricky situation at the moment:

/**
 * @var Coach
 *
 * @Assert\NotNull()
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Coach", fetch="EAGER", inversedBy="events")
 * @Serializer\Expose()
 * @Algolia\Attribute()
 */
private $coach;

But when I try to reindex, I get an error message:

 Tried to index `coach` relation which is a `Proxies\__CG__\AppBundle\Entity\Coach` instance, which is not recognized as an entity to index.

I would like Algolia to index the serialized version of my Coach entity (which has its own serialisation rules).

Is there a trick I could use ? The simplest alternative would be to construct and array with the data I need in a getter but I would just duplicate the work done by the Serializer.

Any idea on how to solve this ? 😃

Call to a member function getProperties() on a non-object

Hi,

After adding @Algolia\Attribute annotation on my properties (protected properties) I tried to index my entity using sf algolia:reindex GamerCertifiedCvBundle:Cv

But that gives me:

PHP Fatal error: Call to a member function getProperties() on a non-object in /Users/tbessoussa/workspace/seekteam/vendor/algolia/algolia-search-bundle/Indexer/Indexer.php on line 407

ldd(self::$indexSettings[$class]);

capture d ecran 2015-10-04 a 11 47 44

Using ^1.0 version (1.0.8).

"symfony/symfony": "2.6.*",
"doctrine/orm": "~2.2,>=2.2.3,<2.5",
"doctrine/dbal": "<2.5",
"doctrine/doctrine-bundle": "~1.2",

[Command line reindex] Issue with custom field methods

When importing objects with some of the information retrievable only through custom methods, the content may or may not be imported.

Example of custom method :

   /**
    * @Algolia\Attribute
    */
   public function creatorName()
   {
       return $this->creator->getName();
   }

Reverse-Routing – Index Urls of entities

In the readme the urlis mentioned in the attributesToIndex

attributesToIndex = {"name", "description", "url"},

Is there any generator for reverse-routing a url?
I didn't find a way to do this and don't want to inject the container or something into my entities for that.

[3.0] Import command via indice name

It could be nice to have the search:import command to accept name of the indice for DX.

So given this config:

 algolia_search:
    indices:
        - name: cv
          class: AppBundle\Entity\Cv

When running:
search:import cv it works out of the box (or even a list of indices to import)

It's better than to write search:import AppBundle:Cv (because AppBundle:Cv doesn't even appear in the configuration)

What do you think ?

Index Relations Symfony

Hei, I'm trying to idex a relation on this way:


/**
     * @ORM\ManyToOne(targetEntity="Specialty", inversedBy="professionals")
     * @ORM\JoinColumn(name="specialty_id", referencedColumnName="id", onDelete="CASCADE")
     * @Algolia\Attribute
     */
    private $specialty; 

But when I run my

php app/console algolia:reindex

Im getting this error:


  [Algolia\AlgoliaSearchBundle\Exception\NotAnAlgoliaEntity]                                                                                           
  Tried to index `specialty` relation which is a `Proxies\__CG__\AppBundle\Entity\Specialty` instance, which is not recognized as an entity to index.

Any help?

Update attribute namings

  • attributesToIndex -> searchableAttributes
  • numericalAttributesToIndex -> numericAttributesForFiltering

Avoid serialization of the objectID

In order to avoid to have to do something like

​$indexer = new Algolia\AlgoliaSearchBundle\Indexer();
​​list($primaryKey, $unusedOldPrimaryKey) = $indexer->getPrimaryKeyForAlgolia($entity);
$index->​getObject($primaryKey);
​```

to get the objectID of a entity

Document schema change behavior

We don't detect schema change, I had an user in support asking why his index was not correctly updated after a schema change. We should just add a small line in the documentation that indicates that a reindexing need to be done after a schema change.

Need to retrieve manually index name from Entity

Hi,

I need to retrieve manually the index name from an Entity, for example I have an entity named "Member" which is indexed. The index name on Algolia is "dev_Member" and I need to have this to generate a secured api key with some filters.

I saw there is a method getAlgoliaIndexName but she is tagged as internal and she doesn't work if this method discoverEntity is not called before.

Please find what I am doing today:

$algoliaIndexer = $this->get('algolia.indexer');
$algoliaIndexer->discoverEntity(Member::class, $em);
$indexName = $algoliaIndexer->getAlgoliaIndexName(Member::class);

What do you think about a public method to get the index name from a entity class as follow:

public function getAlgoliaIndexName2(EntityManager $em, $entityName)
{
    $entityClass = $em->getRepository($entityName)->getClassName();

    if (!$this->discoverEntity($entityClass, $em)) {
         throw new NotAnAlgoliaEntity(
            'Can\'t search, entity of class `'.$entityClass.'` is not recognized as an Algolia enriched entity.'
        );
    }

    return $this->getAlgoliaIndexName($entityClass);
}

Exceptions in algolia code break our code

I'm currently having the following exception thrown from algoliasearch-client-php/src/AlgoliaSearch/Client.php:504:
"AlgoliaSearch\AlgoliaException: Operations quota exceeded, change plan to get more Operations."

We are using a trial plan, it's quite possible I have reached my quota.

Though looking at the stack, this Client code was run by AlgoliaSearchDoctrineEventSubscriber.

This means that every time I use my database via doctrine and update an entity that is indexed in algolia, an exception can be raised by any part of this bundle code (AlgoliaException / \Exception ..). This is not acceptable: our server code will not work any more whenever an exception occurs.

Code in AlgoliaSearchDoctrineEventSubscriber should be within try / catch to avoid any exception bubbling up and breaking our code. I suggest you use the logger to write such exceptions in a log file.

IndexIf ignored for related entities as attributes

Hi, I'm not sure if this is a bug or if it's just a design that I need to work around:

I have an index on an entity A that has a OneToMany relationship with entity B. I put an @algolia\Attribute annotation on that property, and in my entity B I put @algolia\Attribute annotations on the fields that I wanted to include in A's index. Works great! The B entities are pulled in as an array of objects with only the attributes I wanted to include - excellent. (And with the help of the manual indexer I was able to make sure that changes to entity B were incorporated in A's index as well.)

Except - I put an @algolia\IndexIf on one of my methods in entity B that seems to be ignored. I don't have (or want) an index explicitly on entity B, but I would like to pull into my A index only the B objects that meet a specific condition.

So my main question is, is this intended? Is there not a way to conditionally include OneToMany related entities if the @algolia\Attribute tag is used on their property definition? If this is intended, my next move would be to include a custom method in A that returns only the B entities I want to conditionally include, and put the attribute tag there, but I thought I'd check first.

Also, as a general note, I think this bundle is really helpful, and I was relieved to find that I was able to include related entities as attributes - but I discovered that based on reading the previously submitted issue tickets. I think it would be great to note this capability in the README - thanks!

Is it possible to index serialized entities rather then properties directly?

I couldn't find mention of it in the documentation, so I suspect the answer is "no" but I've also seen a few issues kicking around here talking about Serialization.

The particular use case I'm going for is something similar to how the FOSElasticaBundle can be configured, whereby we would pass our entities through the Serializer before it goes to Algolia. This would be great because then we are using the same JSON representation in Algolia search results as what we would usually serve via our API, meaning no database interaction required and clients could even talk directly to Algolia with ease.

Thanks!

Create new tag for fixes

Looks like this is fixed in d7ed4d2 but all the tagged versions, 1.0.0 and 1.0.1 have this issue and was blowing things up for me. Anyway we can get a 1.0.2 tag release that includes this fix. Thanks.

Support Inheritance and Doctrine Mapped Superclasses ?

We have a entity structure with Single Table Inheritance and Doctrine mapped superclasses. However, indexing of properties in such a scenario appears to be not supported.

Are we doing anything wrong or are such configurations not supported ?

Here is an example of our entities

/**
 * Post
 * @ORM\Entity()
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="type", length=10)
 * @ORM\DiscriminatorMap({"question"="Question", "answer"="Answer"})
 */
abstract class Post
{
    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=255, nullable=true)
     * @Algolia\Attribute
     */
    protected $title;
    //...
}
/**
 * Answer
 * 
 * @ORM\Entity()
 */
class Answer extends Post
{
    /**
     * @var bool
     * @ORM\Column(name="votes", type="integer")
     * @Algolia\Attribute
     */
    public $votes;
   //...
}

Expected: Index for Answer should contain the field title too

Private properties in Indexer - can you make them protected?

Hi there

I need to implement a custom Indexer but I'm having some issues with private properties.

Specifically, is there any chance you could make the following properties in the Indexer clas protected rather than private, or perhaps type hint the listener service so it will accept an IndexerInterface rather than only the base class?

 private $entitiesScheduledForCreation = array();
 private $entitiesScheduledForUpdate = array();
 private $entitiesScheduledForDeletion = array();

I can extend the class and inject extra dependencies to add additional data (e.g. CDN urls) without any problems, but I need to be able to access these properties to build a master index... unless there is some other way to do this?

Let me know if that's not clear...

attributesForFaceting

Hi there

I don't believe the attributesForFaceting annotation is working. I have the following mapping but the facets are not created. The indices are populated fine other than the missing facets.

This is using Symfony 2.7.3.

/**
 * Overall Index
 *
 * @ORM\Table(
 *  name="search_overall_index",
 *  indexes = {
 *         @ORM\Index(name="idx_search_class_identifier", columns={"class", "identifier"})
 *      },
 *  uniqueConstraints={
 *     @ORM\UniqueConstraint(columns={"class", "identifier"})
 *    }
 * )
 *
 * @UniqueEntity(fields={"class", "identifier"})
 *
 * @ORM\Entity(repositoryClass="SearchBundle\Repository\OverallRepository")
 * @ORM\HasLifecycleCallbacks
 *
 * @Algolia\Index(
 *     attributesForFaceting = {"type", "user", "project"},
 *     attributeForDistinct = "objectKey"
 * )
 *
 */
class Overall extends BaseEntity
{

  //Other properties and methods: Example mapping for type:

    /**
     * @var string
     *
     * @ORM\Column(name="type", type="string", length=255, nullable=false)
     * @Assert\NotBlank()
     * @Algolia\Attribute(algoliaName="type")
     */
    private $type;

Memory problem when reindexing 21000+ entities

When launching the reindex command on a table containing 21k+ entities, I got this error.

PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 72 bytes) in /app/vendor/algolia/algoliasearch-client-php/src/AlgoliaSearch/Index.php on line 644

This may be due to the fact that the entity manager needs to be cleared between batches.
I'll try to look into it and submit a pull-request.

Best,

Sqlite support

Not sure if sqlite is widely used in the Symfony community, but it's something I like to use to avoid running a MySQL engine. Right now, it seems to be impossible to run the unit tests with pdo_sqlite because it looks for a database_host key.

Do you think we could handle it as well?

    database_driver: pdo_sqlite
    database_path: test.db

setSettings is never called on index creation

Hello,

Use case :

/**
 * Activity
 *
 * @ORM\Table()
 *
 * @Algolia\Index(
 *     attributesForFaceting = "locale"
 * )
 */
class Activity implements Translatable
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

 //Other things

    /**
     * @Algolia\Attribute
     * @Algolia\Id
     * Used locale to override Translation listener`s locale
     * this is not a mapped field of entity metadata, just a simple property
     */
    protected $locale;

//Getters & Setters
}

Expected : app/console algolia:reindex --unsafe MyBundle:Activity should trigger \AlgoliaSearch\Index::setSettings to persist Algolia\Index annotation

Current behavior : My entity is persisted but configuration mismatch. If I set a breakpoint on the setSettings, the function is never called. Is it normal ?

Regards,
Gaël

Return code of the algolia:reindex command not Unix compliant

I added this command at the beginning of my travis build in order to test some search-related features and my build crashes because the return value of the command is equal to the number of entities reindexed.

A quote from the Advanced Bash-Scripting Guide from the Linux documentation project:

Well-behaved UNIX commands, programs, and utilities return a 0 exit code upon successful completion

[Command line reindex] Issue with indexIf

The count of indexed elements is not equal to the number of elements that match the predicate.

Method used

if ($this->approved == self::TEMPLATE_APPROVED) {
           echo self::TEMPLATE_APPROVED; //for debugging purpose
           return ($this->approved == self::TEMPLATE_APPROVED);
}

Any workaround for mapping with yml ?

Hello all,

I am actually trying to convince my client to take Algolia for it's Symfony application. They currently use yml. Is there any way to map entity in this case ?

Cheers

Call to a member function getProperties() on boolean

Hello,

After adding @algolia\Attribute annotation on a property with a ManyToOne assocation I tried to index my entity using app/console algolia:reindex AppBundle:Project.

But this command returns me an error :

PHP Fatal error: Call to a member function getProperties() on boolean in /home/elodie/workspace/my-project/vendor/algolia/algolia-search-bundle/Indexer/Indexer.php on line 407

Here is my entity Project :
https://gist.github.com/elodie-nazaret/acc9765039385ec8f9aa

And there are versions I use :

"symfony/symfony": "2.8.*@dev",
"doctrine/orm": "^2.4.8",
"doctrine/doctrine-bundle": "~1.4",
"algolia/algolia-search-bundle": "^1.0"

Related to issue #27

[3.0] Custom Normalizer is not called

Given a customized Normalizer (that relies on other Normalizers) defined as a service & registered in the Symfony app.
I would expect the search-bundle to use it and but that's not the case.

algolia_search:
    indices:
        - name: cv
          class: AppBundle\Entity\Cv
          normalizers:
            - AppBundle\Serializer\Normalizer\CvNormalizer
<?php

namespace AppBundle\Serializer\Normalizer;

use AppBundle\Entity\Cv;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\SerializerAwareInterface;
use Symfony\Component\Serializer\SerializerAwareTrait;

class CvNormalizer implements NormalizerInterface, SerializerAwareInterface
{
    use SerializerAwareTrait;

    public function normalize($object, $format = null, array $context = [])
    {
        /* @var Cv $object */

        if ($format == 'searchableArray') {
            if ($object->getExpiresAt() < new \DateTime("18 months ago")) {
                return [];
            }
        }

        return [
            'id'        => $object->getId(),
            'name'      => $object->getPseudo(),
            'pseudo'    => $object->getPseudo(),
            'slug'      => $object->getSlug(),
            'createdAt' => $this->serializer->normalize($object->getCreatedAt(), $format, $context),
            'updatedAt' => $this->serializer->normalize($object->getUpdatedAt(), $format, $context),
            'user'      => $this->serializer->normalize($object->getUser(), $format, $context),
            'profiles'  => $this->serializer->normalize($object->getProfiles(), $format, $context),
            'game'      => $this->serializer->normalize($object->getGame(), $format, $context),
            'platform'  => $this->serializer->normalize($object->getPlatform(), $format, $context),
        ];
    }

    public function supportsNormalization($data, $format = null)
    {
        return $data instanceof Cv;
    }
}
<service id="cv_normalizer" class="AppBundle\Serializer\Normalizer\CvNormalizer" public="false">
    <tag name="serializer.normalizer" />
</service>

Result

Default Algolia normalizer is used instead of mine

hosted_cloud_search_as_a_service___algolia

Order Annotation maters for perEnvironment indexation

Hello,

 * @Algolia\Index(autoIndex=true)
 * @Algolia\Index(perEnvironment=false)

=> Works as expected

* @Algolia\Index(perEnvironment=false)
* @Algolia\Index(autoIndex=true)

=> Ignore perEnvironment=false

Is it normal ?

[3.0] Normalizers usage

Hello,

I seen that 3.x uses a new concept to serialize data based on the Symfony serializer which is a great move IMHO.

If I already have a set of normalizer for my objects, BUT i don't want them to be used for Algolia (and use the one I provide instead), is there a way to do this ?

Can I use the normalizers key to provide only "whitelisted" normalizers ?

    - name: comments
      class: App\Entity\Comment
      normalizers:
        - App\Normalizers\CommentNormalizer
        - Symfony\Component\Serializer\Normalizer\CustomNormalizer
        - Algolia\SearchBundle\Normalizer\SearchableArrayNormalizer

Also, in that case I will have 2 normalizer for 1 object Foo

How can I ensure that my previous code still uses the Normalizer I wrote and not uses the one I wrote for Algolia service ?

Related objects are not updated propertly

Hi,

I have some problem with updates. Let's take this object :

{ 'user':
'firstname' : 'john',
'lastname' : 'doe',
'address' : {
'city': 'Paris',
'number': 123
}
}

I want to index "firstname", "lastname" (with an autoIndex on User). I also index this method :

getStringAddress() { return $this->getAddress()->getNumber().' '.$this->getAddress()->getCity();}

but with no autoIndex on Address.

When I create a new object, everythings looks fine. I can retrieve all my fields.

When I update only the firstname, sometimes it looks fine (firstname updated, other fields still here), other times not (firstname updated, other fields disappeared).

When I update the city, in the better case, my object is not updated but still here (here = indexed in the algolia system). In the worst case, all the fields have disappeared.

My analysis is that this method should be bugged (https://github.com/algolia/AlgoliaSearchBundle/blob/master/Indexer/Indexer.php#L229). The line 238 should work in every case (put this line at 232 fixes the problem as the update is now considered at a creation) whereas the 236 does not do the job. This is probably due to the use of the getEntityChangeSet() method (https://github.com/algolia/AlgoliaSearchBundle/blob/master/EventListener/AlgoliaSearchDoctrineEventSubscriber.php#L61) that seems to not take care of related objects.

This analysis explains why the object is not updated when I only update a field on a related object. but it does not explain why some data are removed from the index sometimes...

I wish you luck! :)

Embedded objects (incl. Doctrine embeddables) are not indexed

I've got a doctrine entity that makes use of Doctrine's @Embeddable objects. When I index the entities (using either the Manual Indexer, the Automatic Indexer, or the reindex command), embedded objects end up as null values.

Upon investigation, I noticed that Algolia\AlgoliaSearchBundle\Indexer\Indexer::isEntity() currently enforces only scalar values and Doctrine entities to be indexed, and not other miscellaneous objects, regardless of whether the objects have @Algolia\Index or @Algolia\Attribute annotations.

Wondering if this is intentional?

Could to Index entity, when there is relation with field, that was soft-deleted

In case, when we got DoctrineExtension and turn on SoftDeletable behaviour.
If on related table there is entity, that was deleted, on algolia:reindex command system throw exception like:

php bin/console algolia:reindex CoreBundle:Applications -v
                                                                        
  [Doctrine\ORM\EntityNotFoundException]                                
  Entity of type 'CoreBundle\Entity\User' for IDs id(14) was not found  
            

Exception trace:
 () at /project/vendor/doctrine/orm/lib/Doctrine/ORM/EntityNotFoundException.php:47
 Doctrine\ORM\EntityNotFoundException::fromClassNameAndIdentifier() at /project/vendor/doctrine/orm/lib/Doctrine/ORM/Proxy/ProxyFactory.php:194
 Doctrine\ORM\Proxy\ProxyFactory->Doctrine\ORM\Proxy\{closure}() at /project/var/cache/dev/doctrine/orm/Proxies/__CG__CoreBundleEntityUser.php:1242
 Closure->__invoke() at /project/var/cache/dev/doctrine/orm/Proxies/__CG__CoreBundleEntityUser.php:1242
 Proxies\__CG__\CoreBundle\Entity\User->getCoopter() at /project/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php:483
 Symfony\Component\PropertyAccess\PropertyAccessor->readProperty() at /project/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php:406
 Symfony\Component\PropertyAccess\PropertyAccessor->readPropertiesUntil() at /project/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php:178
 Symfony\Component\PropertyAccess\PropertyAccessor->getValue() at /project/vendor/algolia/algolia-search-bundle/Indexer/Indexer.php:309
 Algolia\AlgoliaSearchBundle\Indexer\Indexer->extractPropertyValue() at /project/vendor/algolia/algolia-search-bundle/Indexer/Indexer.php:439
 Algolia\AlgoliaSearchBundle\Indexer\Indexer->getFieldsForAlgolia() at /project/vendor/algolia/algolia-search-bundle/Indexer/Indexer.php:346
 Algolia\AlgoliaSearchBundle\Indexer\Indexer->extractPropertyValue() at /project/vendor/algolia/algolia-search-bundle/Indexer/Indexer.php:439
 Algolia\AlgoliaSearchBundle\Indexer\Indexer->getFieldsForAlgolia() at /project/vendor/algolia/algolia-search-bundle/Indexer/Indexer.php:493
 Algolia\AlgoliaSearchBundle\Indexer\Indexer->processScheduledIndexChanges() at /project/vendor/algolia/algolia-search-bundle/Indexer/ManualIndexer.php:48
 Algolia\AlgoliaSearchBundle\Indexer\ManualIndexer->doIndex() at /project/vendor/algolia/algolia-search-bundle/Indexer/ManualIndexer.php:139
 Algolia\AlgoliaSearchBundle\Indexer\ManualIndexer->Algolia\AlgoliaSearchBundle\Indexer\{closure}() at /project/vendor/algolia/algolia-search-bundle/Indexer/ManualIndexer.php:97
 Algolia\AlgoliaSearchBundle\Indexer\ManualIndexer->batchQuery() at /project/vendor/algolia/algolia-search-bundle/Indexer/ManualIndexer.php:140
 Algolia\AlgoliaSearchBundle\Indexer\ManualIndexer->index() at /project/vendor/algolia/algolia-search-bundle/Indexer/ManualIndexer.php:259
 Algolia\AlgoliaSearchBundle\Indexer\ManualIndexer->reIndex() at /project/vendor/algolia/algolia-search-bundle/Command/ReindexCommand.php:94
 Algolia\AlgoliaSearchBundle\Command\ReindexCommand->reIndex() at /project/vendor/algolia/algolia-search-bundle/Command/ReindexCommand.php:69
 Algolia\AlgoliaSearchBundle\Command\ReindexCommand->execute() at /project/vendor/symfony/symfony/src/Symfony/Component/Console/Command/Command.php:262
 Symfony\Component\Console\Command\Command->run() at /project/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:848
 Symfony\Component\Console\Application->doRunCommand() at /project/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:190
 Symfony\Component\Console\Application->doRun() at /project/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php:80
 Symfony\Bundle\FrameworkBundle\Console\Application->doRun() at /project/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:121
 Symfony\Component\Console\Application->run() at /project/bin/console:29

Memory problem when reindexing 21000+ entities

When launching the reindex command on a table containing 21k+ entities, I got this error.

PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 72 bytes) in /app/vendor/algolia/algoliasearch-client-php/src/AlgoliaSearch/Index.php on line 644

This may be due to the fact that the entity manager needs to be cleared between batches.
I'll try to look into it and submit a pull-request.

Best,

Boolean value after form submit

There is a difference between two case for a boolean value.
I have a simple symfony form for create and edit a BlogPost entity.

My form

    ->add(
        'visible',
        ChoiceType::class,
        [
                'label' => 'Etat',
                'choices' => [
                        false => 'Brouillon',
                        true => 'En ligne'
                ]
        ]
    )

My entity

    /**
     * @var bool
     *
     * @ORM\Column(name="visible", type="boolean")
     *
     * @Algolia\Attribute
     */
    private $visible;

And now this my index. On the top, the result of the index after form submit. On the bottom, the result after a algolia:reindex command.

screen shot 2017-01-20 at 07 12 13

Facet can't be used for visible:true

How do I disable Algolia in test env?

Tried conditionally register AlgoliaBundle in my AppKernel (so it's available only in prod and dev environments) but then my tests fail due to non-existent services like "algolia.indexer"...

Doesn't seem I can disable Doctrine's listeners in config_test.yml just for AlgoliaBundle. Can I?

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.