t000755000765000024 013066415310 17465 5ustar00nsteenlastaff000000000000Catmandu-Store-Elasticsearch-0.050900.t100644000765000024 43513066415310 20213 0ustar00nsteenlastaff000000000000Catmandu-Store-Elasticsearch-0.0509/t#!/usr/bin/env perl use strict; use warnings; use Test::More; my @pkgs = qw( Catmandu::Store::ElasticSearch Catmandu::Store::ElasticSearch::Bag Catmandu::Store::ElasticSearch::Searcher Catmandu::Store::ElasticSearch::CQL ); require_ok $_ for @pkgs; done_testing 4; Catmandu-Store-Elasticsearch-0.0509000755000765000024 013066415310 17301 5ustar00nsteenlastaff000000000000README100644000765000024 2453513066415310 20273 0ustar00nsteenlastaff000000000000Catmandu-Store-Elasticsearch-0.0509NAME Catmandu::Store::ElasticSearch - A searchable store backed by Elasticsearch SYNOPSIS # From the command line # Import data into ElasticSearch $ catmandu import JSON to ElasticSearch --index-name 'catmandu' < data.json # Export data from ElasticSearch $ catmandu export ElasticSearch --index-name 'catmandu' to JSON > data.json # Export only one record $ catmandu export ElasticSearch --index-name 'catmandu' --id 1234 # Export using an ElasticSearch query $ catmandu export ElasticSearch --index-name 'catmandu' --query "name:Recruitment OR name:college" # Export using a CQL query (needs a CQL mapping) $ catmandu export ElasticSearch --index-name 'catmandu' --q "name any college" # From Perl use Catmandu; my $store = Catmandu->store('ElasticSearch', index_name => 'catmandu'); my $obj1 = $store->bag->add({ name => 'Patrick' }); printf "obj1 stored as %s\n" , $obj1->{_id}; # Force an id in the store my $obj2 = $store->bag->add({ _id => 'test123' , name => 'Nicolas' }); # Commit all changes $store->bag->commit; $store->bag->delete('test123'); $store->bag->delete_all; # All bags are iterators $store->bag->each(sub { ... }); $store->bag->take(10)->each(sub { ... }); # Query the store using a simple ElasticSearch query my $hits = $store->bag->search(query => '(content:this OR name:this) AND (content:that OR name:that)'); # Native queries are also supported by providing a hash of terms # See the ElasticSearch manual for more examples my $hits = $store->bag->search( query => { # All name.exact fields that start with 'test' prefix => { 'name.exact' => 'test' } } , limit => 1000); # Catmandu::Store::ElasticSearch supports CQL... my $hits = $store->bag->search(cql_query => 'name any "Patrick"'); METHODS new(index_name => $name, [...]) new(index_name => $name , index_mapping => \%map, [...]) new(index_name => $name , ... , bags => { data => { cql_mapping => \%map } }) Create a new Catmandu::Store::ElasticSearch store connected to index $name. Optional extra ElasticSearch connection parameters will be passed on to the backend database. Optionally provide an index_mapping which contains a ElasticSearch schema for each field in the index (See below). Optionally provide for each bag a cql_mapping to map fields to CQL indexes. drop Deletes the Elasticsearch index backing this store. Calling functions after this may fail until this class is reinstantiated, creating a new index. INDEX MAP The index_mapping contains a Elasticsearch schema mappings for each bag defined in the index. E.g. { data => { properties => { _id => { type => 'string', include_in_all => 'true', index => 'not_analyzed' } , title => { type => 'string' } } } } In the example above the default 'data' bag of the ElasticSearch contains an '_id' field of type 'string' which is stored automatically also in the '_all' search field. The '_id' is not analyzed. The bag also contains a 'title' field of type string. See https://www.elastic.co/guide/en/elasticsearch/reference/2.2/mapping.html for more information on mappings. These mappings can be passed inside a Perl program, or be written into a Catmandu 'catmandu.yml' configuration file. E.g. # catmandu.yml store: search: package: ElasticSearch options: index_name: catmandu index_mappings data: properties: _id: type: string include_in_all: true index: not_analyzed title: type: string Via the command line these configuration parameters can be read in by using the name of the store, search in this case: $ catmandu import JSON to search < data.json $ catmandu export search to JSON > data.json CQL MAP Catmandu::Store::ElasticSearch supports CQL searches when a cql_mapping is provided for each bag. This hash contains a translation of CQL fields into Elasticsearch searchable fields. # Example mapping { indexes => { title => { op => { 'any' => 1 , 'all' => 1 , '=' => 1 , '<>' => 1 , 'exact' => {field => [qw(mytitle.exact myalttitle.exact)]} } , field => 'mytitle', sort => 1, cb => ['Biblio::Search', 'normalize_title'] } } } The CQL mapping above will support for the 'title' field the CQL operators: any, all, =, <> and exact. The 'title' field will be mapping into the Elasticsearch field 'mytitle', except for the 'exact' operator. In case of 'exact' we will search both the 'mytitle.exact' and 'myalttitle.exact' fields. The CQL mapping allows for sorting on the 'title' field. If, for instance, we would like to use a special ElasticSearch field for sorting we could have written "sort => { field => 'mytitle.sort' }". The callback field cb contains a reference to subroutines to rewrite or augment a search query. In this case, the Biblio::Search package contains a normalize_title subroutine which returns a string or an ARRAY of strings with augmented title(s). E.g. package Biblio::Search; sub normalize_title { my ($self,$title) = @_; my $new_title =~ s{[^A-Z0-9]+}{}g; $new_title; } 1; Also this configuration can be added to a catmandu.yml configuration file like: # catmandu.yml store: search: package: ElasticSearch options: index_name: catmandu index_mappings data: properties: _id: type: string include_in_all: true index: not_analyzed title: type: string bags: data: cql_mapping: indexes: title: op: 'any': true 'all': true '=': true '<>': true 'exact': field: [ 'mytitle.exact' , 'myalttitle.exact' ] field: mytitle sort: true cb: [ 'Biblio::Search' , 'normalize_title' ] } Via the command line these configuration parameters can be read in by using the name of the store, search in this case: $ catmandu export search -q 'title any blablabla' to JSON > data.json COMPATIBILITY This store expects version 1.0 or higher of the Elasticsearch server. To talk to older versions of Elasticsearch the approriate client should be installed. # Elasticsearch 2.x cpanm Search::Elasticsearch::Client::2_0::Direct # Elasticsearch 1.x cpanm Search::Elasticsearch::Client::1_0::Direct And the client version should be specified in the options: Catmandu::Store::ElasticSearch->new(index_name => 'myindex', client => '1_0::Direct') Note that Elasticsearch >= 2.0 doesn't allow keys that start with an underscore such as _id. You can use the key_prefix option at store level or id_prefix at bag level to handle this. # in your catmandu.yml store: yourstore: package: ElasticSearch options: # use my_id instead of _id key_prefix: my_ If you want to use the delete_by_query method with Elasticsearch >= 2.0 you need have to install the delete by query plugin . MIGRATING A STORE FROM ELASTICSEARCH 1.0 TO 2.0 OR HIGHER 1. backup your data as JSON catmandu export yourstore --bag yourbag to --file /path/to/yourbag.json -v 2. drop the store catmandu drop yourstore 3. upgrade the Elasticsearch server 4. update your catmandu.yml with a key_prefix or id_prefix (see COMPATIBILITY) 5. import your data using the new keys specified in your catmandu.yml catmandu import --file /path/to/yourbag.json --fix 'move_field(_id, my_id)' \ to yourstore --bag yourbag -v ERROR HANDLING Error handling can be activated by specifying an error handling callback for index when creating a store. E.g. to create an error handler for the bag 'data' index use: my $store = Catmandu::Store::ElasticSearch->new( index_name => 'catmandu' bags => { data => { on_error => \&error_handler } } }); sub error_handler { my ($action, $response, $i) = @_; } SEE ALSO Catmandu::Store AUTHOR Nicolas Steenlant, CONTRIBUTORS Dave Sherohman, dave.sherohman at ub.lu.se Robin Sheat, robin at kallisti.net.nz Patrick Hochstenbach, patrick.hochstenbach at ugent.be LICENSE AND COPYRIGHT This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License. See http://dev.perl.org/licenses/ for more information. Changes100644000765000024 330613066415310 20657 0ustar00nsteenlastaff000000000000Catmandu-Store-Elasticsearch-0.0509Revision history for Catmandu-Store-ElasticSearch 0.0509 2017-03-28 10:11:49 CEST - escape spaces in query string terms, remove quoting 0.0508 2017-03-23 14:22:20 CET - use Catmandu's new CQLSearchable role - support JSON encoded sort param 0.0507 2017-03-10 14:06:16 CET - Elasticsearch 5.0 iteration compatibility 0.0506 2017-02-23 09:53:51 CET - more pod 0.0505 2017-02-16 15:55:34 CET - correctly quote query string terms 0.0504 2017-01-03 13:35:26 CET - support escaping of special CQL characters 0.0503 2016-12-20 11:38:16 CET - fuzzy CQL queries are now analyzed 0.0502 2016-12-20 11:32:10 CET - fuzzy CQL queries are now analyzed 0.0501 2016-08-23 13:33:19 CEST - minimal pod for all packages 0.05 2016-05-26 11:11:57 CEST - Elasticsearch 2.0 compatibility (if you use a custom key_prefix or id_key) - add the Catmandu::Droppable role to the store and bag 0.04_01 2016-03-15 11:57:49 CET - Elasticsearch 2.0 compatibility (this is only possible by field renaming and needs reindexing) - add the Catmandu::Droppable role to the store and bag 0.0306 2016-01-12 11:21:12 CET - drop support 0.0305 2015-10-15 13:24:08 CEST - fix on_error bug 0.0304 2015-02-06 12:10:05 CET - revert to the Catmandu::Store::ElasticSearch name to avoid installation troubles 0.0303 2015-02-02 11:17:35 CET - [more of nothing] 0.0302 2015-02-02 10:57:13 CET - [nothing] 0.0301 2014-11-20 11:01:09 CET - fix typo 0.03 2014-11-17 10:23:11 CET - fix get missing doc 0.02 2014-11-14 17:17:54 CET - fix error handler bug 0.01 2014-11-06 10:26:12 CET - Continue development from Catmandu::Store::ElasticSearch with the official Search::Elasticsearch client LICENSE100644000765000024 4367413066415310 20425 0ustar00nsteenlastaff000000000000Catmandu-Store-Elasticsearch-0.0509This software is copyright (c) 2017 by Nicolas Steenlant. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2017 by Nicolas Steenlant. This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2017 by Nicolas Steenlant. This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End cpanfile100644000765000024 51513066415310 21047 0ustar00nsteenlastaff000000000000Catmandu-Store-Elasticsearch-0.0509requires 'perl', 'v5.10.1'; on 'test', sub { requires 'Test::Simple', '1.001003'; requires 'Test::More', '1.001003'; }; requires 'Catmandu', '>=1.04'; requires 'Cpanel::JSON::XS', '>=3.0213'; requires 'CQL::Parser', '1.12'; requires 'Moo', '1.0'; requires 'namespace::clean', '0.24'; requires 'Search::Elasticsearch', '1.14'; dist.ini100644000765000024 4213066415310 20762 0ustar00nsteenlastaff000000000000Catmandu-Store-Elasticsearch-0.0509[@Milla] installer = ModuleBuild Build.PL100644000765000024 246513066415310 20665 0ustar00nsteenlastaff000000000000Catmandu-Store-Elasticsearch-0.0509 # This file was automatically generated by Dist::Zilla::Plugin::ModuleBuild v6.008. use strict; use warnings; use Module::Build 0.28; my %module_build_args = ( "build_requires" => { "Module::Build" => "0.28" }, "configure_requires" => { "Module::Build" => "0.28" }, "dist_abstract" => "A searchable store backed by Elasticsearch", "dist_author" => [ "Nicolas Steenlant, C<< >>" ], "dist_name" => "Catmandu-Store-Elasticsearch", "dist_version" => "0.0509", "license" => "perl", "module_name" => "Catmandu::Store::Elasticsearch", "recursive_test_files" => 1, "requires" => { "CQL::Parser" => "1.12", "Catmandu" => "1.04", "Cpanel::JSON::XS" => "3.0213", "Moo" => "1.0", "Search::Elasticsearch" => "1.14", "namespace::clean" => "0.24", "perl" => "v5.10.1" }, "test_requires" => { "Test::More" => "1.001003", "Test::Simple" => "1.001003" } ); my %fallback_build_requires = ( "Module::Build" => "0.28", "Test::More" => "1.001003", "Test::Simple" => "1.001003" ); unless ( eval { Module::Build->VERSION(0.4004) } ) { delete $module_build_args{test_requires}; $module_build_args{build_requires} = \%fallback_build_requires; } my $build = Module::Build->new(%module_build_args); $build->create_build_script; META.yml100644000765000024 252313066415310 20635 0ustar00nsteenlastaff000000000000Catmandu-Store-Elasticsearch-0.0509--- abstract: 'A searchable store backed by Elasticsearch' author: - 'Nicolas Steenlant, C<< >>' build_requires: Module::Build: '0.28' Test::More: '1.001003' Test::Simple: '1.001003' configure_requires: Module::Build: '0.28' dynamic_config: 0 generated_by: 'Dist::Milla version v1.0.17, Dist::Zilla version 6.008, CPAN::Meta::Converter version 2.150005' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Catmandu-Store-Elasticsearch no_index: directory: - eg - examples - inc - share - t - xt requires: CQL::Parser: '1.12' Catmandu: '1.04' Cpanel::JSON::XS: '3.0213' Moo: '1.0' Search::Elasticsearch: '1.14' namespace::clean: '0.24' perl: v5.10.1 resources: bugtracker: https://github.com/LibreCat/Catmandu-Store-Elasticsearch/issues homepage: https://github.com/LibreCat/Catmandu-Store-Elasticsearch repository: https://github.com/LibreCat/Catmandu-Store-Elasticsearch.git version: '0.0509' x_contributors: - 'Dave Sherohman ' - 'Nicolas Steenlant ' - 'Nicolas Steenlant ' - 'Patrick Hochstenbach ' - 'Robin Sheat ' x_serialization_backend: 'YAML::Tiny version 1.69' MANIFEST100644000765000024 53513066415310 20476 0ustar00nsteenlastaff000000000000Catmandu-Store-Elasticsearch-0.0509# This file was automatically generated by Dist::Zilla::Plugin::Manifest v6.008. Build.PL Changes LICENSE MANIFEST META.json META.yml README cpanfile dist.ini lib/Catmandu/Store/ElasticSearch.pm lib/Catmandu/Store/ElasticSearch/Bag.pm lib/Catmandu/Store/ElasticSearch/CQL.pm lib/Catmandu/Store/ElasticSearch/Searcher.pm t/00.t t/author-pod-syntax.t META.json100644000765000024 441413066415310 21006 0ustar00nsteenlastaff000000000000Catmandu-Store-Elasticsearch-0.0509{ "abstract" : "A searchable store backed by Elasticsearch", "author" : [ "Nicolas Steenlant, C<< >>" ], "dynamic_config" : 0, "generated_by" : "Dist::Milla version v1.0.17, Dist::Zilla version 6.008, CPAN::Meta::Converter version 2.150005", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "Catmandu-Store-Elasticsearch", "no_index" : { "directory" : [ "eg", "examples", "inc", "share", "t", "xt" ] }, "prereqs" : { "build" : { "requires" : { "Module::Build" : "0.28" } }, "configure" : { "requires" : { "Module::Build" : "0.28" } }, "develop" : { "requires" : { "Dist::Milla" : "v1.0.17", "Test::Pod" : "1.41" } }, "runtime" : { "requires" : { "CQL::Parser" : "1.12", "Catmandu" : "1.04", "Cpanel::JSON::XS" : "3.0213", "Moo" : "1.0", "Search::Elasticsearch" : "1.14", "namespace::clean" : "0.24", "perl" : "v5.10.1" } }, "test" : { "requires" : { "Test::More" : "1.001003", "Test::Simple" : "1.001003" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/LibreCat/Catmandu-Store-Elasticsearch/issues" }, "homepage" : "https://github.com/LibreCat/Catmandu-Store-Elasticsearch", "repository" : { "type" : "git", "url" : "https://github.com/LibreCat/Catmandu-Store-Elasticsearch.git", "web" : "https://github.com/LibreCat/Catmandu-Store-Elasticsearch" } }, "version" : "0.0509", "x_contributors" : [ "Dave Sherohman ", "Nicolas Steenlant ", "Nicolas Steenlant ", "Patrick Hochstenbach ", "Robin Sheat " ], "x_serialization_backend" : "Cpanel::JSON::XS version 3.0225" } author-pod-syntax.t100644000765000024 45413066415310 23403 0ustar00nsteenlastaff000000000000Catmandu-Store-Elasticsearch-0.0509/t#!perl BEGIN { unless ($ENV{AUTHOR_TESTING}) { print qq{1..0 # SKIP these tests are for testing by the author\n}; exit } } # This file was automatically generated by Dist::Zilla::Plugin::PodSyntaxTests. use strict; use warnings; use Test::More; use Test::Pod 1.41; all_pod_files_ok(); Store000755000765000024 013066415310 22620 5ustar00nsteenlastaff000000000000Catmandu-Store-Elasticsearch-0.0509/lib/CatmanduElasticSearch.pm100644000765000024 2574213066415310 26062 0ustar00nsteenlastaff000000000000Catmandu-Store-Elasticsearch-0.0509/lib/Catmandu/Storepackage Catmandu::Store::ElasticSearch; use Catmandu::Sane; our $VERSION = '0.0509'; use Moo; use Search::Elasticsearch; use Catmandu::Util qw(is_instance); use Catmandu::Store::ElasticSearch::Bag; use namespace::clean; with 'Catmandu::Store'; with 'Catmandu::Droppable'; has index_name => (is => 'ro', required => 1); has index_settings => (is => 'ro', lazy => 1, default => sub { +{} }); has index_mappings => (is => 'ro', lazy => 1, default => sub { +{} }); has _es_args => (is => 'rw', lazy => 1, default => sub { +{} }); has es => (is => 'lazy'); # used internally has is_es_1_or_2 => (is => 'lazy'); sub _build_es { my ($self) = @_; my $es = Search::Elasticsearch->new($self->_es_args); unless ($es->indices->exists(index => $self->index_name)) { $es->indices->create( index => $self->index_name, body => { settings => $self->index_settings, mappings => $self->index_mappings, }, ); } $es; } sub BUILD { my ($self, $args) = @_; $self->_es_args($args); } sub drop { my ($self) = @_; $self->es->indices->delete(index => $self->index_name); } sub _build_is_es_1_or_2 { my ($self) = @_; is_instance($self->es, 'Search::Elasticsearch::Client::1_0::Direct') || is_instance($self->es, 'Search::Elasticsearch::Client::2_0::Direct'); } 1; __END__ =pod =head1 NAME Catmandu::Store::ElasticSearch - A searchable store backed by Elasticsearch =head1 SYNOPSIS # From the command line # Import data into ElasticSearch $ catmandu import JSON to ElasticSearch --index-name 'catmandu' < data.json # Export data from ElasticSearch $ catmandu export ElasticSearch --index-name 'catmandu' to JSON > data.json # Export only one record $ catmandu export ElasticSearch --index-name 'catmandu' --id 1234 # Export using an ElasticSearch query $ catmandu export ElasticSearch --index-name 'catmandu' --query "name:Recruitment OR name:college" # Export using a CQL query (needs a CQL mapping) $ catmandu export ElasticSearch --index-name 'catmandu' --q "name any college" # From Perl use Catmandu; my $store = Catmandu->store('ElasticSearch', index_name => 'catmandu'); my $obj1 = $store->bag->add({ name => 'Patrick' }); printf "obj1 stored as %s\n" , $obj1->{_id}; # Force an id in the store my $obj2 = $store->bag->add({ _id => 'test123' , name => 'Nicolas' }); # Commit all changes $store->bag->commit; $store->bag->delete('test123'); $store->bag->delete_all; # All bags are iterators $store->bag->each(sub { ... }); $store->bag->take(10)->each(sub { ... }); # Query the store using a simple ElasticSearch query my $hits = $store->bag->search(query => '(content:this OR name:this) AND (content:that OR name:that)'); # Native queries are also supported by providing a hash of terms # See the ElasticSearch manual for more examples my $hits = $store->bag->search( query => { # All name.exact fields that start with 'test' prefix => { 'name.exact' => 'test' } } , limit => 1000); # Catmandu::Store::ElasticSearch supports CQL... my $hits = $store->bag->search(cql_query => 'name any "Patrick"'); =head1 METHODS =head2 new(index_name => $name, [...]) =head2 new(index_name => $name , index_mapping => \%map, [...]) =head2 new(index_name => $name , ... , bags => { data => { cql_mapping => \%map } }) Create a new Catmandu::Store::ElasticSearch store connected to index $name. Optional extra ElasticSearch connection parameters will be passed on to the backend database. Optionally provide an C which contains a ElasticSearch schema for each field in the index (See below). Optionally provide for each bag a C to map fields to CQL indexes. =head2 drop Deletes the Elasticsearch index backing this store. Calling functions after this may fail until this class is reinstantiated, creating a new index. =head1 INDEX MAP The index_mapping contains a Elasticsearch schema mappings for each bag defined in the index. E.g. { data => { properties => { _id => { type => 'string', include_in_all => 'true', index => 'not_analyzed' } , title => { type => 'string' } } } } In the example above the default 'data' bag of the ElasticSearch contains an '_id' field of type 'string' which is stored automatically also in the '_all' search field. The '_id' is not analyzed. The bag also contains a 'title' field of type string. See L for more information on mappings. These mappings can be passed inside a Perl program, or be written into a Catmandu 'catmandu.yml' configuration file. E.g. # catmandu.yml store: search: package: ElasticSearch options: index_name: catmandu index_mappings data: properties: _id: type: string include_in_all: true index: not_analyzed title: type: string Via the command line these configuration parameters can be read in by using the name of the store, C in this case: $ catmandu import JSON to search < data.json $ catmandu export search to JSON > data.json =head1 CQL MAP Catmandu::Store::ElasticSearch supports CQL searches when a cql_mapping is provided for each bag. This hash contains a translation of CQL fields into Elasticsearch searchable fields. # Example mapping { indexes => { title => { op => { 'any' => 1 , 'all' => 1 , '=' => 1 , '<>' => 1 , 'exact' => {field => [qw(mytitle.exact myalttitle.exact)]} } , field => 'mytitle', sort => 1, cb => ['Biblio::Search', 'normalize_title'] } } } The CQL mapping above will support for the 'title' field the CQL operators: any, all, =, <> and exact. The 'title' field will be mapping into the Elasticsearch field 'mytitle', except for the 'exact' operator. In case of 'exact' we will search both the 'mytitle.exact' and 'myalttitle.exact' fields. The CQL mapping allows for sorting on the 'title' field. If, for instance, we would like to use a special ElasticSearch field for sorting we could have written "sort => { field => 'mytitle.sort' }". The callback field C contains a reference to subroutines to rewrite or augment a search query. In this case, the Biblio::Search package contains a normalize_title subroutine which returns a string or an ARRAY of strings with augmented title(s). E.g. package Biblio::Search; sub normalize_title { my ($self,$title) = @_; my $new_title =~ s{[^A-Z0-9]+}{}g; $new_title; } 1; Also this configuration can be added to a catmandu.yml configuration file like: # catmandu.yml store: search: package: ElasticSearch options: index_name: catmandu index_mappings data: properties: _id: type: string include_in_all: true index: not_analyzed title: type: string bags: data: cql_mapping: indexes: title: op: 'any': true 'all': true '=': true '<>': true 'exact': field: [ 'mytitle.exact' , 'myalttitle.exact' ] field: mytitle sort: true cb: [ 'Biblio::Search' , 'normalize_title' ] } Via the command line these configuration parameters can be read in by using the name of the store, C in this case: $ catmandu export search -q 'title any blablabla' to JSON > data.json =head1 COMPATIBILITY This store expects version 1.0 or higher of the Elasticsearch server. To talk to older versions of Elasticsearch the approriate client should be installed. # Elasticsearch 2.x cpanm Search::Elasticsearch::Client::2_0::Direct # Elasticsearch 1.x cpanm Search::Elasticsearch::Client::1_0::Direct And the client version should be specified in the options: Catmandu::Store::ElasticSearch->new(index_name => 'myindex', client => '1_0::Direct') Note that Elasticsearch >= 2.0 doesn't allow keys that start with an underscore such as C<_id>. You can use the C option at store level or C at bag level to handle this. # in your catmandu.yml store: yourstore: package: ElasticSearch options: # use my_id instead of _id key_prefix: my_ If you want to use the C method with Elasticsearch >= 2.0 you need have to L. =head1 MIGRATING A STORE FROM ELASTICSEARCH 1.0 TO 2.0 OR HIGHER 1. backup your data as JSON catmandu export yourstore --bag yourbag to --file /path/to/yourbag.json -v 2. drop the store catmandu drop yourstore 3. upgrade the Elasticsearch server 4. update your catmandu.yml with a C or C (see COMPATIBILITY) 5. import your data using the new keys specified in your catmandu.yml catmandu import --file /path/to/yourbag.json --fix 'move_field(_id, my_id)' \ to yourstore --bag yourbag -v =head1 ERROR HANDLING Error handling can be activated by specifying an error handling callback for index when creating a store. E.g. to create an error handler for the bag 'data' index use: my $store = Catmandu::Store::ElasticSearch->new( index_name => 'catmandu' bags => { data => { on_error => \&error_handler } } }); sub error_handler { my ($action, $response, $i) = @_; } =head1 SEE ALSO L =head1 AUTHOR Nicolas Steenlant, C<< >> =head1 CONTRIBUTORS =over 4 =item Dave Sherohman, C<< dave.sherohman at ub.lu.se >> =item Robin Sheat, C<< robin at kallisti.net.nz >> =item Patrick Hochstenbach, C<< patrick.hochstenbach at ugent.be >> =back =head1 LICENSE AND COPYRIGHT This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License. See http://dev.perl.org/licenses/ for more information. =cut ElasticSearch000755000765000024 013066415310 25332 5ustar00nsteenlastaff000000000000Catmandu-Store-Elasticsearch-0.0509/lib/Catmandu/StoreBag.pm100644000765000024 1570313066415310 26547 0ustar00nsteenlastaff000000000000Catmandu-Store-Elasticsearch-0.0509/lib/Catmandu/Store/ElasticSearchpackage Catmandu::Store::ElasticSearch::Bag; use Catmandu::Sane; our $VERSION = '0.0509'; use Moo; use Catmandu::Hits; use Cpanel::JSON::XS qw(decode_json); use Catmandu::Store::ElasticSearch::Searcher; use Catmandu::Store::ElasticSearch::CQL; with 'Catmandu::Bag'; with 'Catmandu::Droppable'; with 'Catmandu::CQLSearchable'; has buffer_size => (is => 'ro', lazy => 1, builder => 'default_buffer_size'); has _bulk => (is => 'ro', lazy => 1, builder => '_build_bulk'); has cql_mapping => (is => 'ro'); has on_error => (is => 'ro', default => sub { sub {} }); sub default_buffer_size { 100 } sub _build_bulk { my ($self) = @_; my %args = ( index => $self->store->index_name, type => $self->name, max_count => $self->buffer_size, on_error => \&{$self->on_error}, ); if ($self->log->is_debug) { $args{on_success} = sub { my ($action, $res, $i) = @_; # TODO return doc instead of index $self->log->debug($res); }; } $self->store->es->bulk_helper(%args); } sub generator { my ($self) = @_; sub { state $scroll = do { my %args = ( index => $self->store->index_name, type => $self->name, size => $self->buffer_size, # TODO divide by number of shards body => { query => {match_all => {}}, }, ); if ($self->store->is_es_1_or_2) { $args{search_type} = 'scan'; } $self->store->es->scroll_helper(%args); }; my $data = $scroll->next // do { $scroll->finish; return; }; $data->{_source}; }; } sub count { my ($self) = @_; $self->store->es->count( index => $self->store->index_name, type => $self->name, )->{count}; } sub get { my ($self, $id) = @_; try { $self->store->es->get_source( index => $self->store->index_name, type => $self->name, id => $id, ); } catch_case [ 'Search::Elasticsearch::Error::Missing' => sub { undef } ]; } sub add { my ($self, $data) = @_; $data = {%$data}; my $id = $data->{$self->id_key}; $self->_bulk->index({ id => $id, source => $data, }); } sub delete { my ($self, $id) = @_; $self->_bulk->delete({id => $id}); } sub delete_all { my ($self) = @_; my $es = $self->store->es; if ($es->can('delete_by_query')) { $es->delete_by_query( index => $self->store->index_name, type => $self->name, body => { query => {match_all => {}}, }, ); } else { # TODO document plugin needed for es >= 2.0 $es->transport->perform_request( method => 'DELETE', path => '/'.$self->store->index_name.'/'.$self->name.'/_query', body => { query => {match_all => {}}, } ); } } sub delete_by_query { my ($self, %args) = @_; my $es = $self->store->es; if ($es->can('delete_by_query')) { $es->delete_by_query( index => $self->store->index_name, type => $self->name, body => { query => $args{query}, }, ); } else { # TODO document plugin needed for es >= 2.0 $es->transport->perform_request( method => 'DELETE', path => '/'.$self->store->index_name.'/'.$self->name.'/_query', body => { query => $args{query}, } ); } } sub commit { my ($self) = @_; $self->_bulk->flush; $self->store->es->transport->perform_request( method => 'POST', path => '/'.$self->store->index_name.'/_refresh', ); } sub search { my ($self, %args) = @_; my $id_key = $self->id_key; my $start = delete $args{start}; my $limit = delete $args{limit}; my $bag = delete $args{reify}; if ($bag) { $args{fields} = []; } my $res = $self->store->es->search( index => $self->store->index_name, type => $self->name, body => { %args, from => $start, size => $limit, }, ); my $docs = $res->{hits}{hits}; my $hits = { start => $start, limit => $limit, total => $res->{hits}{total}, }; if ($bag) { $hits->{hits} = [ map { $bag->get($_->{$id_key}) } @$docs ]; } elsif ($args{fields}) { $hits->{hits} = [ map { $_->{fields} || +{} } @$docs ]; } else { $hits->{hits} = [ map { $_->{_source} } @$docs ]; } $hits = Catmandu::Hits->new($hits); for my $key (qw(facets suggest aggregations)) { $hits->{$key} = $res->{$key} if exists $args{$key}; } if ($args{highlight}) { for my $hit (@$docs) { if (my $hl = $hit->{highlight}) { $hits->{highlight}{$hit->{$id_key}} = $hl; } } } $hits; } sub searcher { my ($self, %args) = @_; Catmandu::Store::ElasticSearch::Searcher->new(%args, bag => $self); } sub translate_sru_sortkeys { my ($self, $sortkeys) = @_; [ grep { defined $_ } map { $self->_translate_sru_sortkey($_) } split /\s+/, $sortkeys ]; } sub _translate_sru_sortkey { my ($self, $sortkey) = @_; my ($field, $schema, $asc) = split /,/, $sortkey; $field || return; if (my $map = $self->cql_mapping) { $field = lc $field; $field =~ s/(?<=[^_])_(?=[^_])//g if $map->{strip_separating_underscores}; $map = $map->{indexes} || return; $map = $map->{$field} || return; $map->{sort} || return; if (ref $map->{sort} && $map->{sort}{field}) { $field = $map->{sort}{field}; } elsif (ref $map->{field}) { $field = $map->{field}->[0]; } elsif ($map->{field}) { $field = $map->{field}; } } $asc //= 1; +{ $field => $asc ? 'asc' : 'desc' }; } sub translate_cql_query { my ($self, $query) = @_; Catmandu::Store::ElasticSearch::CQL->new(mapping => $self->cql_mapping, id_key => $self->id_key)->parse($query); } sub normalize_query { my ($self, $query) = @_; if (ref $query) { $query; } elsif ($query) { {query_string => {query => $query}}; } else { {match_all => {}}; } } # assume a sort string is JSON encoded sub normalize_sort { my ($self, $sort) = @_; return $sort if ref $sort; return if !$sort; decode_json($sort); } sub drop { my ($self) = @_; $self->delete_all; $self->commit; } 1; __END__ =pod =head1 NAME Catmandu::Store::ElasticSearch::Bag - Catmandu::Bag implementation for Elasticsearch =head1 DESCRIPTION This class isn't normally used directly. Instances are constructed using the store's C method. =head1 SEE ALSO L, L =cut CQL.pm100644000765000024 2426113066415310 26474 0ustar00nsteenlastaff000000000000Catmandu-Store-Elasticsearch-0.0509/lib/Catmandu/Store/ElasticSearchpackage Catmandu::Store::ElasticSearch::CQL; use Catmandu::Sane; our $VERSION = '0.0509'; use Catmandu::Util qw(require_package trim); use CQL::Parser; use Moo; use namespace::clean; has parser => (is => 'ro', lazy => 1, builder => '_build_parser'); has mapping => (is => 'ro', required => 1); has id_key => (is => 'ro', required => 1); my $RE_ANY_FIELD = qr'^(srw|cql)\.(serverChoice|anywhere)$'i; my $RE_MATCH_ALL = qr'^(srw|cql)\.allRecords$'i; my $RE_DISTANCE_MODIFIER = qr'\s*\/\s*distance\s*<\s*(\d+)'i; sub _build_parser { CQL::Parser->new; } sub parse { my ($self, $query) = @_; my $node = eval { $self->parser->parse($query); } or do { my $error = $@; die "cql error: $error"; }; $self->parse_node($node); } sub parse_node { my ($self, $node) = @_; my $query = {}; unless ($node->isa('CQL::BooleanNode')) { $node->isa('CQL::TermNode') ? $self->_parse_term_node($node, $query) : $self->_parse_prox_node($node, $query); return $query; } my @stack = ($node); my @query_stack = (my $q = $query); while (@stack) { $node = shift @stack; $q = shift @query_stack; if ($node->isa('CQL::BooleanNode')) { push @stack, $node->left, $node->right; push @query_stack, my $left = {}, my $right = {}; if ($node->op eq 'and') { $q->{bool} = { must => [$left, $right] }; } elsif ($node->op eq 'or') { $q->{bool} = { should => [$left, $right] }; } else { $q->{bool} = { must => [ $left, { bool => { must_not => [$right] } } ] }; } } elsif ($node->isa('CQL::TermNode')) { $self->_parse_term_node($node, $q); } else { $self->_parse_prox_node($node, $q); } } $query; } sub _parse_term_node { my ($self, $node, $query) = @_; my $term = $node->getTerm; if ($term =~ $RE_MATCH_ALL) { return { match_all => {} }; } my $qualifier = $node->getQualifier; my $relation = $node->getRelation; my @modifiers = $relation->getModifiers; my $base = lc $relation->getBase; if ($base eq 'scr') { if ($self->mapping and my $rel = $self->mapping->{default_relation}) { $base = $rel; } else { $base = '='; } } if ($qualifier =~ $RE_ANY_FIELD) { if ($self->mapping and my $idx = $self->mapping->{default_index}) { $qualifier = $idx; } else { $qualifier = '_all'; } } my $nested; if ($self->mapping and my $indexes = $self->mapping->{indexes}) { $qualifier = lc $qualifier; $qualifier =~ s/(?<=[^_])_(?=[^_])//g if $self->mapping->{strip_separating_underscores}; my $mapping = $indexes->{$qualifier} or Catmandu::Error->throw("cql error: unknown index $qualifier"); $mapping->{op}{$base} or Catmandu::Error->throw("cql error: relation $base not allowed"); my $op = $mapping->{op}{$base}; if (ref $op && $op->{field}) { $qualifier = $op->{field}; } elsif ($mapping->{field}) { $qualifier = $mapping->{field}; } my $filters; if (ref $op && $op->{filter}) { $filters = $op->{filter}; } elsif ($mapping->{filter}) { $filters = $mapping->{filter}; } if ($filters) { for my $filter (@$filters) { if ($filter eq 'lowercase') { $term = lc $term; } } } if (ref $op && $op->{cb}) { my ($pkg, $sub) = @{$op->{cb}}; $term = require_package($pkg)->$sub($term); } elsif ($mapping->{cb}) { my ($pkg, $sub) = @{$mapping->{cb}}; $term = require_package($pkg)->$sub($term); } $nested = $mapping->{nested}; } # TODO just pass query around my $es_node = $self->_term_node($base, $qualifier, $term, @modifiers); if ($nested) { if ($nested->{query}) { $es_node = { bool => { must => [ $nested->{query}, $es_node, ] } }; } $es_node = { nested => { path => $nested->{path}, query => $es_node, } }; } for my $key (keys %$es_node) { $query->{$key} = $es_node->{$key}; } $query; } sub _parse_prox_node { my ($self, $node, $query) = @_; my $slop = 0; my $qualifier = $node->left->getQualifier; my $term = join(' ', $node->left->getTerm, $node->right->getTerm); if (my ($n) = $node->op =~ $RE_DISTANCE_MODIFIER) { $slop = $n - 1 if $n > 1; } if ($qualifier =~ $RE_ANY_FIELD) { $qualifier = '_all'; } $query->{match_phrase} = { $qualifier => { query => $term, slop => $slop } }; } sub _term_node { my ($self, $base, $qualifier, $term, @modifiers) = @_; my $q; if ($base eq '=') { if (ref $qualifier) { return { bool => { should => [ map { if ($_ eq $self->id_key) { { ids => { values => [$term] } }; } else { $self->_text_node($_, $term, @modifiers); } } @$qualifier ] } }; } else { if ($qualifier eq $self->id_key) { return { ids => { values => [$term] } }; } return $self->_text_node($qualifier, $term, @modifiers); } } elsif ($base eq '<') { if (ref $qualifier) { return { bool => { should => [ map { { range => { $_ => { lt => $term } } } } @$qualifier ] } }; } else { return { range => { $qualifier => { lt => $term } } }; } } elsif ($base eq '>') { if (ref $qualifier) { return { bool => { should => [ map { { range => { $_ => { gt => $term } } } } @$qualifier ] } }; } else { return { range => { $qualifier => { gt => $term } } }; } } elsif ($base eq '<=') { if (ref $qualifier) { return { bool => { should => [ map { { range => { $_ => { lte => $term } } } } @$qualifier ] } }; } else { return { range => { $qualifier => { lte => $term } } }; } } elsif ($base eq '>=') { if (ref $qualifier) { return { bool => { should => [ map { { range => { $_ => { gte => $term } } } } @$qualifier ] } }; } else { return { range => { $qualifier => { gte => $term } } }; } } elsif ($base eq '<>') { if (ref $qualifier) { return { bool => { must_not => [ map { if ($_ eq $self->id_key) { { ids => { values => [$term] } }; } else { { match_phrase => { $_ => { query => $term } } }; } } @$qualifier ] } }; } else { if ($qualifier eq $self->id_key) { return { bool => { must_not => [ { ids => { values => [$term] } } ] } }; } return { bool => { must_not => [ { match_phrase => { $qualifier => { query => $term } } } ] } }; } } elsif ($base eq 'exact') { if (ref $qualifier) { return { bool => { should => [ map { if ($_ eq $self->id_key) { { ids => { values => [$term] } }; } else { { match_phrase => { $_ => { query => $term } } }; } } @$qualifier ] } }; } else { if ($qualifier eq $self->id_key) { return { ids => { values => [$term] } }; } return {match_phrase => { $qualifier => { query => $term } } }; } } elsif ($base eq 'any') { $term = [split /\s+/, trim($term)]; if (ref $qualifier) { return { bool => { should => [ map { $q = $_; map { $self->_text_node($q, $_) } @$term; } @$qualifier ] } }; } else { if ($qualifier eq $self->id_key) { return { ids => { values => $term } }; } return { bool => { should => [map { $self->_text_node($qualifier, $_) } @$term] } }; } } elsif ($base eq 'all') { $term = [split /\s+/, trim($term)]; if (ref $qualifier) { return { bool => { should => [ map { $q = $_; { bool => { must => [map { $self->_text_node($q, $_) } @$term] } }; } @$qualifier ] } }; } else { return { bool => { must => [map { $self->_text_node($qualifier, $_) } @$term] } }; } } elsif ($base eq 'within') { my @range = split /\s+/, $term; if (@range == 1) { if (ref $qualifier) { return { bool => { should => [ map { { text => { $_ => { query => $term } } } } @$qualifier ] } }; } else { return { match => { $qualifier => { query => $term } } }; } } if (ref $qualifier) { return { bool => { should => [ map { { range => { $_ => { lte => $range[0], gte => $range[1] } } } } @$qualifier ] } }; } else { return { range => { $qualifier => { lte => $range[0], gte => $range[1] } } }; } } if (ref $qualifier) { return { bool => { should => [ map { $self->_text_node($_, $term, @modifiers); } @$qualifier ] } }; } else { return $self->_text_node($qualifier, $term, @modifiers); } } sub _text_node { my ($self, $qualifier, $term, @modifiers) = @_; if ($term =~ /[^\\][\*\?]/) { # escape spaces $term =~ s/(? { query => qq|$qualifier:$term| } }; } # Unescape wildcards (when needed)... $term =~ s{[\\]([\^\*\?])}{$1}g; for my $m (@modifiers) { if ($m->[1] eq 'fuzzy') { # TODO only works for single terms, mapping fuzzy_factor return { fuzzy => { $qualifier => { value => $term, max_expansions => 10 } } }; } } if ($term =~ /\s/) { return { match_phrase => { $qualifier => { query => $term } } }; } { match => { $qualifier => { query => $term } } }; } 1; Searcher.pm100644000765000024 425313066415310 27570 0ustar00nsteenlastaff000000000000Catmandu-Store-Elasticsearch-0.0509/lib/Catmandu/Store/ElasticSearchpackage Catmandu::Store::ElasticSearch::Searcher; use Catmandu::Sane; our $VERSION = '0.0509'; use Moo; use namespace::clean; with 'Catmandu::Iterable'; has bag => (is => 'ro', required => 1); has query => (is => 'ro', required => 1); has start => (is => 'ro', required => 1); has limit => (is => 'ro', required => 1); has total => (is => 'ro'); has sort => (is => 'ro'); sub generator { my ($self) = @_; my $store = $self->bag->store; sub { state $total = $self->total; if (defined $total) { return unless $total; } state $scroll = do { my $body = {query => $self->query}; $body->{sort} = $self->sort if $self->sort; my %args = ( index => $store->index_name, type => $self->bag->name, from => $self->start, size => $self->bag->buffer_size, # TODO divide by number of shards body => $body, ); if (!$self->sort && $store->is_es_1_or_2) { $args{search_type} = 'scan'; } $store->es->scroll_helper(%args); }; my $data = $scroll->next // do { $scroll->finish; return; }; if ($total) { $total--; } $data->{_source}; }; } sub slice { # TODO constrain total? my ($self, $start, $total) = @_; $start //= 0; $self->new( bag => $self->bag, query => $self->query, start => $self->start + $start, limit => $self->limit, total => $total, sort => $self->sort, ); } sub count { my ($self) = @_; my $store = $self->bag->store; $store->es->count( index => $store->index_name, type => $self->bag->name, body => { query => $self->query, }, )->{count}; } 1; __END__ =pod =head1 NAME Catmandu::Store::ElasticSearch::Bag - Searcher implementation for Elasticsearch =head1 DESCRIPTION This class isn't normally used directly. Instances are constructed using the store's C method. =head1 SEE ALSO L =cut