PHP elasticsearch learning record

catalogue

I ElasticSearch installation

1. Download ElasticSearch (window) server

 2.PHP install es extension

II ElasticSearch property Word introduction

III Introduction to elasticsearch PHP API

Document address: https://www.elastic.co/guide/cn/index.html

Learning record based on window

I ElasticSearch installation

1. Download ElasticSearch (window) server

①. Download address: https://www.elastic.co/cn/downloads/elasticsearch Downloads window version

②. Download to the local directory. The structure is as follows: double click to open elasticsearch. Com under bin Bat enable es service

③. Browser access 127.0 0.1:9200 is as follows: installation succeeded

 2.PHP install es extension

①. The es extension must be installed based on composer. If it is not installed, you need to install composer first

Move the installation of composer to https://www.runoob.com/w3cnote/composer-install-and-usage.html

②. Install es extensions

Create a new folder "ES" under the project address, such as "WWW", and call out the command line under "cmd" under the "ES" directory to execute:

composer require elasticsearch/elasticsearch

③. After installation, create a new "index.php" in the "ES" directory as follows:

 ④. Access the project address in the browser to view the print information, as shown below, indicating that the configuration is successful.

II ElasticSearch property Word introduction

took: how many milliseconds did the request take

 _ shards: query fragment information

Hits: the search result. Total is the total number of satisfied documents, and hits is the actual number returned (10 by default)

 max_score and_ Score: the score value of the query result. The higher the score, the greater the weight and the higher the ranking

Range: range lookup

term: accurate search

'bool' combines various other queries through 'must' (must and), 'must_not' (must not), and 'should' (should or)

There are many conditions for finding assembly: go to the official website. I feel that the assembly conditions are the core of es

Easy to remember, compared with mysql

III Introduction to elasticsearch PHP API

Description of mapping data:
Field name: fill in any field. Many attributes are specified below, such as title, subtitle, images and price
Type: type. Elasticsearch supports a wide range of data types. There are several key points:
There are two types of String:
text: separable words
keyword: non separable word. The data will be matched as a complete field
Numerical: numerical type, divided into two categories
Basic data types: long, integer, short, byte, double, float, half_float
High precision type of floating point number: scaled_float
Date: date type
Array: array type
Object: object
Index: whether to index. The default value is true, which means that all fields will be indexed without any configuration.
true: if the field is indexed, it can be used for search
false: the field will not be indexed and cannot be used for search
Store: whether to store data independently. The default value is false
The original text is stored in the_ In source, by default, other extracted fields are not stored independently, but from_ Extracted from source. Of course, you can also store a field independently, as long as you set "store": true, it is more difficult to obtain the independently stored field than from_ Source parsing is much faster, but it also takes up more space, so it should be set according to the actual business needs
analyzer: word splitter, ik here_ max_ Word uses ik participle

Create index $client - > indexes() - > create()

$params = [
	'index' => 'user_index', //Index name
	'body' => [
		'settings'=> [ //to configure
			'number_of_shards'=> 3,//Number of main segments
			'number_of_replicas'=> 1 //Number of copies of primary partition
		],
		'mappings'=> [  //mapping                   
				'_source'=>[   //  Store original document
					'enabled' => 'true'
				],
				'properties'=> [ //Configuration data structure and type
					'userid'=> [ //Field 1
						'type'=>'integer',
						'index'=> 'false',
					],
					'username'=> [ //Field 1
						'type'=>'text',//Type text, integer, float, double, boolean, date
						'index'=> 'true',//Index
					],
					'age'=> [ //Field 2
						'type'=>'integer',
					],
					'sex'=> [ //Field 3
						'type'=>'keyword',
					],
				]
			
		],
	]
];
$data = $client->indices()->create($params);

Get index information $client - > indexes() - > getsettings()

$params = [
    'index' => 'user_index',
    'client' => [
        'ignore' => [404,400]//Ignore can ignore the exception. Its value is the return code corresponding to the exception to be ignored. The common 400 indicates that the index already exists and 404 indicates that the index is not found
    ]
];
$res = $client->indices()->getSettings($params);//Get library index setting information

Get Mapping information $client - > indexes() - > getmapping()

$params = [
    'index' => 'user_index',
    'client' => [
        'ignore' => [404,400]//Ignore can ignore the exception. Its value is the return code corresponding to the exception to be ignored. The common 400 indicates that the index already exists and 404 indicates that the index is not found
    ]
];
$res = $client->indices()->getMapping($params);   //Get mapping information

Adding mapping information $client - > indices() - > putmapping()

//Note: the established field type cannot be changed!!

$params = [
    'index' => 'user_index',  //Index name (equivalent to mysql database)
    'body'  =>  [          
		'properties'=> [ //Configuration data structure and type
			'height'=> [ 
				'type'=>'integer',
			],
		]
	],
];
$res = $client->indices()->putMapping($params);

Delete index $client - > indexes() - > delete()

$params = [
    'index' => 'user_index',  //Index name (equivalent to mysql database)
];
$res = $client->indices()->delete($params);

Insert a piece of data $client - > index()

$params = [
    'index' => 'user_index',
    'id' => 'user_id', // If it is not filled in, es will automatically generate a unique id
    'body'  => ['userid'=>1,'username' => 'Zhang San','age'=>42,'sex'=>'male']
];
$res = $client->index($params);

Update a piece of data $client - > update()

$params = [  
    'index' => 'user_index',
    'id' => '39',
    'body' => [  
        'doc' => [  // You must take this with you Indicates a document operation
            'age' => 150  
        ]  
    ]  
];  
$res = $client->update($params); 

Delete a document $client - > delete()

$params = [
    'index' => 'user_index',
    'id'    => 'user_id'
];
$res = $client->delete($params);

Batch insert index data $client - > bulk ()

$params = [];
for($i = 1; $i < 40; $i++) {  
	$params['body'][] = [
		'index' => [
			'_index' => 'user_index',
			'_id'    => $i,
		]
	];  
	$params['body'][] = [ 
		'userid' => $i,
		'username' => 'programming'.$i,  
		'sex' => $i%2 ? 'male' : 'female',
		'age'=>(20+$i),
	];
}  
$res = $client->bulk($params);

Paging query + highlight + conditional query + sort $client - > search()

$params = [
    'index' => 'user_index', 
];
$params['body'] = array(
    'query' => array(
    	'match' => array(
	            'sex' => 'male'
	    ), 
    ),
	'from' => '0',  // Paging starts at 0 by default. from = (pageNum - 1) * size (page - 1) * number of entries per page, page 1: (1-1) * 2 = 0, page 2: (2-1) * 2 = 2
    'size' => '5', // The number of pages is 10 by default
    'sort' => array(  // sort
        'age' => 'desc'   //Sort the age field in descending order  
    ),  
    'highlight' => array( //I didn't understand. I didn't see any change
        'fields' => array(
            'username' => new \stdClass() //Empty object [] / / another way to write (elegant)
        )
    )
);
 
$res = $client->search($params);

json query $client - > search()

$params = [
    'index' => 'user_index',
];
$json='{
  "query": {
    "bool": {
      "must": { "match_all": {} }
    }
  },
  "sort" : { "age" : "desc" },
  "size" : 10 
}';
$params['body'] = $json;
$res = $client->search($params);

Using json query, you can refer to https://blog.csdn.net/robinhunan/article/details/106693313

Compound query $client - > search()

$query = [
    'query' => [
        'bool' => [
            'must' => [
                'match' => [
                    'username' => 'Compile',
                ],
                'match' => [
                    'sex' => 'male',
                ]
            ],
            'filter' => [
                'range' => [
                    'age' => ['gt' => 76]
                ]
            ]
        ]
    ]
];
$params = [
    'index' => 'user_index',
//  'index' = >'m * '#index can be fuzzy matched, and even this parameter is optional
    '_source' => ['username','age','sex'], // Request specified fields
    'body' => array_merge([
        'from' => 0,
        'size' => 5
    ],$query)
];
$res = $client->search($params);

Keywords: PHP ElasticSearch

Added by starmikky on Fri, 17 Dec 2021 15:07:54 +0200