Elasticsearch is referred to as ES for short below
To use ES as a search engine, first we need to install it
Elastic requires the Java 8 environment. Check the Java environment before installing the software
The installation
$ wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.5.1.zip
$ unzip elasticsearch-5.5.1.zip
$ cdElasticsearch 5.5.1 /Copy the code
Next, go to the unzipped directory and run the following command to try to start Elastic
$ ./bin/elasticsearch
Copy the code
Note:
It is very likely that the following error will occur during the initial installation:
max virtual memory areas vm.maxmapcount [65530] is too low
Copy the code
To resolve the problem, run the following command:
$ sudo sysctl -w vm.max_map_count=262144
Copy the code
If all is well, elastic will be running on port 9200 of the machine by default. Requesting this port will give you the following information
$ curl localhost:9200
{
"name" : "atntrTf",
"cluster_name" : "elasticsearch",
"cluster_uuid" : "tf9250XhQ6ee4h7YI11anA",
"version" : {
"number" : "5.5.1",
"build_hash" : "19c13d0",
"build_date" : "2017-07-18T20:44:24.823Z",
"build_snapshot" : false,
"lucene_version" : "6.6.0"
},
"tagline" : "You Know, for Search"
}
Copy the code
By default, elastic only allows local access. If remote access is required, modify the config/ Elasticserach. yml file in the Elastic installation directory to uncomment netword.host and change it to 0.0.0.0. And then restart Elastic
Network. The host: 0.0.0.0Copy the code
In the code above, set it to 0.0.0.0 so that anyone can access it. Don’t do this for online services. Set it to a specific IP address
The basic concept
Elastic is essentially a distributed database that allows multiple servers to work together. Each server can allow multiple Elastic instances. A single Elastic instance is called a node, and a group of nodes forms a cluster
It has some important concepts
- Index = Index
- Type (Type)
- Document
- Shards
- Replicasedit
Shards and replicas are not needed at the moment, so this is a brief explanation
- Copies are multiplications, more is more wasteful, but also more safe. - Sharding is a division method. The more shards there are, the smaller and more fragmented the single shard data is.Copy the code
Since there are many concepts in it, I have posted two very good blogs:
- Ruan Yifeng
- Technical analysis of ElastSearch
After that, we can use a comparison to understand the important concepts
- Relational Databases -> Databases -> Tables -> Rows -> Columns - Elasticsearch -> Indeces -> Types -> Documents -> FieldsCopy the code
An Elasticsearch cluster can contain multiple indexes, each index can contain multiple Types, each type can contain multiple documents, then each document can contain multiple Fields.
Although the analogy is so, they are two different products after all, and it has been mentioned above that Types may be deleted in the later version, so generally we create an index for each type. Fresh creates an index for groceries, and groceries creates an index for groceries, rather than creating an index for groceries that includes both fresh and groceries.
Laravel scout and es
Install the Scout package first
composer require laravel/scout
Copy the code
Generates a configuration file
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
Copy the code
In provider of config/app.php, add
Laravel\Scout\ScoutServiceProvider::class,
ScoutEngines\Elasticsearch\ElasticsearchProvider::class,
Copy the code
Then we also need to add the es configuration information in scoute.php after algolia
'elasticsearch'= > ['index' => env('ELASTICSEARCH_INDEX'.'dongdianyi'),
'hosts' => [
env('ELASTICSEARCH_HOST'.'http://127.0.0.1:9200'),]],Copy the code
We also need to use GuzzleHttp
Install the
composer require guzzlehttp/guzzle
Copy the code
To start writing code, use Command to get ES to initialize some data
php artisan make:command InitEs
Copy the code
Post my code
namespace App\Console\Commands;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
class ESInit extends Command
{
protected $signature = 'es:init';
protected $description = 'Initialize the ES library';
public function __construct(a)
{
parent::__construct();
}
public function handle(a)
{
$client = new Client();
try {
$this->createTemplate($client);
$this->createIndex($client);
} catch (\Exception$ex) { $ex->message(); }}public function createTemplate(Client $client)
{
$url = config('scout.elasticsearch.hosts') [0].'/_template/tmp';
// Ensure that template does not exist
// $client->delete($url);
$param = [
'json'= > ['template'= >The '*'.'settings'= > ['number_of_shards'= >1,].'mappings'= > ['_default_'= > ['_all'= > ['enabled'= >true,].'dynamic_templates' => [
[
'strings'= > ['match_mapping_type'= >'string'.'mapping'= > ['type'= >'text'.'analyzer'= >'ik_smart'.'ignore_above'= >256.'fields'= > ['keyword'= > ['type'= >'keyword'[,], [,], [,],]; $client->put($url, $param);$this->info('elasticsearch template created done');
}
public function createIndex(Client $client)
{
/ / create the index
$url = config('scout.elasticsearch.hosts') [0].'/' . config('scout.elasticsearch.index');
// Make sure index does not exist
// $client->delete($url);
$param = [
'json'= > ['settings'= > ['refresh_interval'= >'5s'.'number_of_shards'= >1.'number_of_replicas'= >0,].'mappings'= > ['_default_'= > ['_all'= > ['enabled'= >false[,] [,],]; $client->put($url, $param);$this->info('elasticsearch index created done'); }}Copy the code
Then, we specify which model needs to be searched
namespace App;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
class Article extends Model
{
use Searchable;
protected $table = 'posts';
protected $fillable = [
'url'.'author'.'title'.'content'.'post_date'
];
public function toSearchableArray(a)
{
return [
'title'= >$this->title,
'content'= >$this->content ]; }}Copy the code
Inside the model, use Searchable and override the toSearchableArray function
Then use the command
php artisan scout:import "App\Article"
Copy the code
The current database data, according to toSearchableArray rules import, import complete can
The verification results
The ES and Scout steps are complete and ready to use
Start by defining the GraphQL interface
searchArticles(keyWord: String!). : [Article!] ! @paginate(defaultCount:10.builder: "App\\Article@searchArticles")
Copy the code
And then parse it
public function searchArticles($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
{
$query = $args['keyWord'];
return Article::search($query);
}
Copy the code
Done! In this example, I use IK_smart, which will automatically match according to the maximum granularity of Chinese word segmentation