la-haute-societe / craft-elasticsearch

Bring the power of Elasticsearch to your Craft CMS projects
Other
18 stars 14 forks source link

Weight fields #4

Closed hiasl closed 5 years ago

hiasl commented 5 years ago

Hi, short question: is it possible to give different fields a different weight for the search score? second question: can a certain result be boosted with a factor? thanks, Matthias

juban commented 5 years ago

Hi Matthias,

Yes, absolutely!

Based on current Elasticsearch documentation here, if you want to boost let's say the title field, you could add something like the following code in a module of your application to alter the default index mapping created by the plugin:

Event::on(ElasticsearchRecord::class, ElasticsearchRecord::EVENT_BEFORE_CREATE_INDEX, function (Event $event) {
    /** @var ElasticsearchRecord $esRecord */
    $esRecord = $event->sender;
    $schema = $esRecord->getSchema();
    $schema['mappings']['elasticsearch-record']['properties']['title']['boost'] = 2;
    $esRecord->setSchema($schema);
});

If you want to set something like that on a custom additional field of yours, you could simply define that in the elasticsearch.php configuration file (see) like the following:

return [
    'extraFields'            => [
        // add your additional field(s)
        'somefield'     => [
            // Define the mapping definition you need for your field
            'mapping' => [
                'type' => 'keyword',
                'boost' => 2, // Whatever boost value that suits
            ],
            'value'   => function (\craft\base\ElementInterface $element, \lhs\elasticsearch\records\ElasticsearchRecord $esRecord) {
               return 'Some value'; // Obviously useless, but you get the idea
            }
        ]
    ]
];

If you want to do that on a query level, you could alter the query directive (see lhs\elasticsearch\record\ElasticsearchRecord::EVENT_BEFORE_SEARCH) to implement a boosting query as described here

I hope I could answer your questions and thank you for your interest in our plugin.

Alban.

juban commented 5 years ago

Ho @hiasl,

Did you managed to achieve what you want? Please, let us know.

hiasl commented 5 years ago

Hey @juban ,

thanks for asking: to be honest, we did not try yet. I needed the information for a quotation where we also offered your extension as part of the service. So let's hope we get the contract, then I will let you know :-)

all the best, Matthias

juban commented 5 years ago

Excellent! Let us know if you need further assistance. Thanks.