/**
* 创建索引 设置索引中的配置 映射关系
* 在使用Elasticsearch-php API的时候,参数$params一般是用数组来,因为数组结构能很方便的转换为json。其中
*_default_是默认配置,其他配置的缺省值都与_default_的相同。
* _all设置true会将所有原始文档拼接在一起额外存储,
* _source设置为true会存储原始文档,设置false一般用在只需要索引出文档的标题或者Url,通过Url去访问文档,而不需要在es中保存一份文档内容的场景。
* 最后,注意同一index下不同type中的同名称字段的数据类型与配置也必须相同!
* 文档可以视作数据库中的行
*/
public function createIndexAction()
{
try {
$client = new EsClientService();
$client = $client->client();
$params = [
'index' => 'supplier_index1',//索引名称 (可以视作库) *************************创建时填写******************************
// 'body' => [
// 'settings'=> [ //配置
// 'number_of_shards'=> 3,//主分片数
// 'number_of_replicas'=> 1 //主分片的副本数
// ]
// 'articles_type' => [ //开启文档
// '_source' => [
// 'enabled' => true
// ],
// 'properties' => [ //字段
// 'id' => [
// 'type' => 'integer'
// ],
// 'ids'=> [
// 'type' => 'integer'
// ],
// 'member_ids' => [
// 'type' => 'text',
// 'analyzer' => 'ik_max_word',
// 'fielddata'=> true
// ],
// 'name' => [
// 'type' => 'text',
// 'analyzer' => 'ik_max_word'
// ],
// 'mobile' => [
// 'type' =>
// ]
// ]
// ]
// 6.x
// 'mappings'=> [ //映射
// '_default_' => [ //默认配置,每个类型缺省的配置使用默认配置
// '_all'=>[ // 关闭所有字段的检索
// 'enabled' => 'false'
// ],
// '_source'=>[ // 存储原始文档
// 'enabled' => 'true'
// ],
// 'properties'=> [ //配置数据结构与类型
// 'bank_name'=> [ //字段1
// 'type'=>'string',//类型 string、integer、float、double、boolean、date
// 'index'=> 'analyzed',//索引是否精确值 analyzed not_analyzed 分词器
// ],
// 'bank_code'=> [ //字段2
// 'type'=>'integer',
// ],
// 'name_initial'=> [ //字段3
// 'type'=>'string',
// 'index'=> 'not_analyzed',
// ],
//
// ]
// ],
// 'order000_type' => [ //文档设置 (表)
// 'properties' => [ //属性
// 'bank_name'=> [ //字段名
// 'type'=>'string', //字段类型
// "fielddata"=> true
// ],
// ]
// ],
// ],
//7.x 可以用 但这里设置的是index 不是type 在7.x中存在默认的type _doc type可以不设置 毕竟要删除 一对一的type
// "mappings" => [
// "properties" => [
// 'id' => ["type" => "text", "analyzer" => "ik_smart"],
// 'ids' => ["type" => "text", "analyzer" => "ik_smart"],
// 'member_ids' => ["type" => "text", "analyzer" => "ik_smart"],
// 'name' => ["type" => "text", "analyzer" => "ik_max_word"],
// ]
// ]
// ]
];
$res = $client->indices()->create($params); //可以先不设置body
print_r($res);
die;
}
catch
(\Exception $e) {
echo "<pre>";
print_r($e->getMessage());
echo "</pre>";
die;
}
}
public function delAction()
{
try{
$client = new EsClientService();
$client = $client->client();
$params = ['index' => 'supplier_index1'];
$response = $client->indices()->delete($params);
print_r($response);
die;
}catch (\Exception $e){
$e->getMessage();
}
}
//动态创建 实现批量插入
public function CreateAction()
{
try {
创建索引(数据库) 如果存在会报错
// $params = [
// 'index' => 'articles_index', #index的名字不能是大写和下划线开头
// 'body' => [
// 'settings' => [
// 'number_of_shards' => 2,
// 'number_of_replicas' => 0
// ]
// ]
// ];
// $this->client->indices()->create($params);
//
// //添加表和字段
//
// $params = [
// 'index' => 'articles_index',
// 'type' => 'articles_type',//文档名(表名)
// 'body' => [
// 'articles_type' => [ //开启文档
// '_source' => [
// 'enabled' => true
// ],
// 'properties' => [ //字段
// 'id' => [
// 'type' => 'integer'
// ],
// 'title' => [
// 'type' => 'text',
// 'analyzer' => 'ik_max_word'//中文分词器
// ],
// 'content' => [
// 'type' => 'text',
// 'analyzer' => 'ik_max_word'
// ]
// ]
// ]
// ]
// ];
// $this->client->indices()->putMapping($params);
$client = new EsClientService();
$client = $client->client();
$supplier = Supplier::init();
$lists = $supplier->getList([],['id','ids','member_ids','name','mobile','pwd','contact','address','bank_name','card' ,'licence','brand','status','created_at','updated_at' ]);
foreach ($lists as $row) {
$params = [
'id' => 'supplier'.$row['id'] ,
'index' => 'supplier_index',
'type' => 'supplier_type',
'body' => [
'id' => $row['id'],
'ids' => $row['ids'],
'member_ids'=> $row['member_ids'],
'name'=> $row['name'],
]
];
$client->index($params);//这里会自动执行上面屏蔽的内容,但是分析器不确定是否要设置
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
public function getAction()
{
$client = new EsClientService();
$client = $client->client();
$params = [
'index' => 'supplier_index',
'type' => 'supplier_type',
'id' => 'supplier9'
];
$res = $client->get($params);
print_r($res);
}
public function SearchAction()
{
try{
$client = new EsClientService();
$client = $client->client();
$params = [
'index' => 'supplier_index',
'type' => 'supplier_type',
'body' => [
'query'=>[
'match_all'=> new \stdClass()
]
]
];
$res = $client->search($params);
print_r($res);
}catch (\Exception $e){
$e->getMessage();
}
}
public function esBulsAction()
{
$client = new EsClientService();
$client = $client->client();
$model=new Payment();
$lists=$model->getList([],['id','name'],'id ASC');
$params['body'] = [];
foreach ($lists as $k=> $v) {
$params['body'][] = [
'index' => [ #创建
'_index' => 'my_index',
'_type' => 'my_type',
'_id' => $k,
],
];
$params['body'][] = [
'name' => $v['name'],
];
}
$res = $client->bulk($params);
//
// $params = [
// 'index' => 'my_index',
// 'type' => 'my_type',
// 'body' => [
// 'query' => [
// "exists"=> [
// "field"=>"name" //字段搜索
// ]
// ]
// ]
// ];
// $params = [
// 'index' => 'my_index',
// 'type' => 'my_type',
// 'body' => [
// 'query' => [
// "te"=> [
// "name"=>"支付"
// ]
// ]
// ]
// ];
// $rt = $client->search($params);
// print_r($rt);
}
public function testAction(){
try{
$client = new EsClientService();
$client = $client->client();
$params = [
'index' => 'my_index',
'type' => 'my_type',
'body' => [
'query' => [
"match"=> [ //分词模糊查询
"name"=>"余付"
]
]
]
];
$rt = $client->search($params);
echo "<pre>";
print_r($rt);
echo "</pre>";
} catch (\Exception $e) {
echo "<pre>";
print_r($e->getMessage());
echo "</pre>";die;
}
}
/**
* 获取指定id文档中的_sourc中的存储数据,获取到的格式如下:
* Array
(
[name] => 微信支付
)
*/
public function getSourceAction()
{
$client = new EsClientService();
$client = $client->client();
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => 1
];
$res = $client->getSource($params);//获取指定id的文档中的_source中的数据
print_r($res);
die;
}
/**
* 获取指定索引的映射关系
*以下为默认(动态创建时)
* Array
(
[supplier_index] => Array
(
[mappings] => Array
(
[properties] => Array
(
[address] => Array //字段名为address
(
[type] => text
[fields] => Array //字段属性设置
(
[keyword] => Array
* (
[type] => keyword
[ignore_above] => 256
)
)
)
)
* )
)
)
*/
public function getMappingsAction()
{
$client = new EsClientService();
$client = $client->client();
$params = [
'index' => 'supplier_index',
];
$res = $client->indices()->getMapping($params);
print_r($res);
die;
}
/**
* 必须先创建索引
* 修改Mappings
* 注意:修改Mappings的API必须要指明type,且只能添加,不能修改已有的属性。
*/
public function putMappingsAction(){
try{
$client = new EsClientService();
$client = $client->client();
$params = [
'index' => 'supplier1_index',
'type' => 'supplier_type',//必须指明类型名
'include_type_name' => true,
'body' => [
'supplier_type' => [ //开启文档
'_source' => [
'enabled' => true
],
'properties' => [ //字段
'id' => ["type" => "text", "analyzer" => "ik_smart"],
'name' => ["type" => "text", "analyzer" => "ik_max_word"],
'mobile' => ["type" => "text", "analyzer" => "ik_smart"],
'pwd' => ["type" => "text", "analyzer" => "ik_smart"],
'contact' => ["type" => "text", "analyzer" => "ik_max_word"],
]
]
]
];
$res = $client->indices()->putMapping($params);
print_r($res);
die;
} catch (\Exception $e) {
echo "<pre>";
print_r($e->getMessage());
echo "</pre>";die;
}
}
public function test2Action(){
try{
$client = new EsClientService();
$client = $client->client();
$params = [
'index' => 'my_index',
'type' => 'my_type',
'body' => [
'query' => [
"match"=> [ //分词模糊查询
"name"=>"余付"
]
]
]
];
$rt = $client->search($params);
echo "<pre>";
print_r($rt);
echo "</pre>";
} catch (\Exception $e) {
echo "<pre>";
print_r($e->getMessage());
echo "</pre>";die;
}
}
public function setBankDataAction()
{
try {
$client = new EsClientService();
$client = $client->client();
$model = new Bank();
$lists = $model->getList([], ['bank_code', 'bank_name', 'name_initial']);
$params['body'] = [];
foreach ($lists as $k => $v) {
$params['body'][] = [
'create' => [ #创建
'_index' => 'order000_index',
'_type' => 'order000_type',
'_id' => $k,
]
];
$params['body'][] = [
'bank_code' => $v['bank_code'],
'bank_name' => $v['bank_name'],
'bank_initial' => $v['bank_initial']
];
}
$res = $client->bulk($params);
// $params = [
// 'index' => 'my_index',
// 'type' => 'my_type',
// 'body' => [
// 'query' => [
// "te"=> [
// "name"=>"支付"
// ]
// ]
// ]
// ];
// $rt = $client->search($params);
print_r($res);
} catch (\Exception $e) {
echo "<pre>";
print_r($e->getMessage());
echo "</pre>";
die;
}
}
public function useJsonGetAction()
{
$client = new EsClientService();
$client = $client->client();
// $json = '{
// "query" : {
// "match" : {
// "bank_name" : "银行"
// }
// }
// }';
$json = '{
"query": {
"bool": {
"should": [{
"match": {
"products.category": "饮料"
}
}, {
"term": {
"buyer": "xl"
}
}],
"must": [{
"range": {
"status": {
"gt": 0
}
}
}],
"filter": {
"range": {
"date": {
"gt": "2019-03-13 11:14:00"
}
}
}
}
}
}';
$params = [
'index' => 'order00_index',
'type' => 'order00_type',
'body' => $json
];
$results = $client->search($params);
print_r($results);
}
public function getDataRangeAction()
{
try{
$client = new EsClientService();
$client = $client->client();
// $json = '{
// "query": {
// "bool": {
// "must": {
// "match": {
// "bank_name": "toothbrush"
// }
// },
// "filter": {
// "range": {
// "name_initial": {
// "gt": "C",
// "lt": "V"
// }
// }
// }
// }
// }
// }';
$params = [
'index' => 'order000_index',
'type' => 'order000_type',
'body' => [
'query'=>[
'bool'=>[
'must'=>[
'match'=>[
'bank_name'=>'银行',
]
],
// 'filter'=>[
// 'range'=>[
// 'name_initial'=>[
// 'gt'=>'C',
// 'lt'=>'V'
// ]
// ]
// ]
]
],
"sort" => [
// "_score"=>"asc" //按照_score由小到大排序
"_score"=>"desc"
// "_source"=>[//不行
// "name_initial"=>"desc"
// ]
]
]
];
$results = $client->search($params);
print_r($results);
die;
}catch (\Exception $e){
echo "<pre>";
print_r($e->getMessage());
echo "</pre>";die;
}
}
//条件查询 should与must不能同时使用,若同时使用,则只有must起作用
public function getDataLikeAction()
{
try{
$client = new EsClientService();
$client = $client->client();
$json = '{
"index":"order00_index",
"type":"order00_type",
"body":{
"query": {
"bool": {
"should":[{"match":{"bank_name": "包"}},{"match":{"name_initial":"A"}}],
"must": {
"match": {
"name_initial":"Z"
}
}
}
}
}
}';
$array = json_decode($json,true);
print_r($array);
//这里的*没用 等同于match查询
// $params = [
// 'index' => 'order00_index',
// 'type' => 'order00_type',
// 'body' => [
// 'query' => [
// 'wildcard' => [
// "bank_name" =>"山*",
// ]
// ]
// ]
// ];
$results = $client->search($array);
print_r($results);
}catch (\Exception $e){
echo "<pre>";
print_r($e->getMessage());
echo "</pre>";die;
}
}
/**
* 少量数据分页显示
*/
public function es_searchAction()
{
try {
$client = new EsClientService();
$client = $client->client();
$data["index"] = "supplier_index2";
$data["type"] = "supplier_type";
[$page, $pageSize, $offset] = $this->getPagingParams();
$data["body"] = array(
"query" =>
array("bool" =>
array("must" =>
array("match_all" => new \stdClass())
)
)
);
// pagesize/from
$data["body"]["size"] = $pageSize;
$data["body"]["from"] = ($page - 1) * $pageSize;
$data = $client->search($data);
print_r($data);
} catch (\Exception $e) {
echo "<pre>";
print_r($e->getMessage());
echo "</pre>";
}
}
public function indextestAction()
{
$client = new EsClientService();
$client = $client->client();
$page = $_REQUEST['page'] ?? 2;
$size = $_REQUEST['size'] ?? 2;
$searchParams = array(
'index' => 'supplier_index',
'type' => 'supplier_type',
"scroll" => "1m", //增加_scroll_id
"size" => $size,
);
$docs = $client->search($searchParams);
$scroll_id = $docs['_scroll_id'];
$i = 1;
if ($page == 1) {
echo "<pre>";
print_r($docs);
echo "</pre>";
}
while ($i < $page) {
$response = $client->scroll(
array(
"scroll_id" => $scroll_id,
"scroll" => "1m"
)
);
if (count($response['hits']['hits']) > 0) { //判断是否查到了数据
$scroll_id = $response['_scroll_id'];
} else {
break;
}
$i++;
}
echo "<pre>";
print_r($response);
echo "</pre>";
}
<?php
namespace Wjp\Controllers;
use Base\BaseController;
use Model\Es\Articles;
use Model\SjxBusiness\Supplier;
use Model\SjxGoods\Goods;
use Model\SjxOrder\Payment;
use Model\SjxTotalOrder\TotalOrderGoods;
use Model\SjxUser\Bank;
use PDO;
use Elasticsearch\ClientBuilder;
use phpDocumentor\Reflection\Type;
use Service\EsClientService;
class SearchController extends BaseController
{
public function indextestAction()
{
$client = ClientBuilder::create()->setHosts(['192.168.2.110:9200'])->build();
$page = $_REQUEST['page'] ?? 1;
$size = $_REQUEST['size'] ?? 2;
$params = [
'index' => 'index',
'type' => 'type',
'body' => [
'query' => [
"match" => [ //分词模糊查询
"title" => "余"
]
]
]
];
$searchParams = array(
'index' => 'index',
'type' => 'type',
'body' => [
'query' => [
"match" => [ //分词模糊查询
"title" => "余"
]
]
],
// "search_type" => "QUERY_THEN_FETCH",
"scroll" => "1m",
"size" => $size,
// "from" => $page*$size
);
$searchParams['body'] = array(#查询条件
);
$docs = $client->search($searchParams);
$scroll_id = $docs['_scroll_id'];
$i = 1;
if ($page == 1) {
echo "<pre>";
print_r($docs);
echo "</pre>";
}
while ($i < $page) {
$response = $client->scroll(
array(
"scroll_id" => $scroll_id,
"scroll" => "1m"
)
);
if (count($response['hits']['hits']) > 0) {
// Do Work Here
// Get new scroll_id
$scroll_id = $response['_scroll_id'];
} else {
break;
}
$i++;
}
return (array(
'code' => 1,
'data' => $response['hits']['hits']
));
}
/**
* 创建索引 设置索引中的配置 映射关系
* 在使用Elasticsearch-php API的时候,参数$params一般是用数组来,因为数组结构能很方便的转换为json。其中
*_default_是默认配置,其他配置的缺省值都与_default_的相同。
* _all设置true会将所有原始文档拼接在一起额外存储,
* _source设置为true会存储原始文档,设置false一般用在只需要索引出文档的标题或者Url,通过Url去访问文档,而不需要在es中保存一份文档内容的场景。
* 最后,注意同一index下不同type中的同名称字段的数据类型与配置也必须相同!
* 文档可以视作数据库中的行
*/
public function createIndexAction()
{
try {
$client = new EsClientService();
$client = $client->client();
$params = [
'index' => 'supplier_index1',//索引名称 (可以视作库) *************************创建时填写******************************
// 'body' => [
// 'settings'=> [ //配置
// 'number_of_shards'=> 3,//主分片数
// 'number_of_replicas'=> 1 //主分片的副本数
// ]
//
/* 以下在kibana中使用*/
// PUT /user/
//
//{
// "megacorp": {
// "aliases": {},
// "mappings": {},
// "settings": {
// "index": {
// "creation_date": "1558956839146",
// "number_of_shards": "5",
// "number_of_replicas": "1",
// "uuid": "pGBqNmxrR1S8I7_jAYdvBA",
// "version": {
// "created": "6060199"
// },
// "provided_name": "megacorp"
// }
// }
// }
//}
// 'articles_type' => [ //开启文档
// '_source' => [
// 'enabled' => true
// ],
// 'properties' => [ //字段
// 'id' => [
// 'type' => 'integer'
// ],
// 'ids'=> [
// 'type' => 'integer'
// ],
// 'member_ids' => [
// 'type' => 'text',
// 'analyzer' => 'ik_max_word',
// 'fielddata'=> true
// ],
// 'name' => [
// 'type' => 'text',
// 'analyzer' => 'ik_max_word'
// ],
// 'mobile' => [
// 'type' =>
// ]
// ]
// ]
// 6.x
// 'mappings'=> [ //映射
// '_default_' => [ //默认配置,每个类型缺省的配置使用默认配置
// '_all'=>[ // 关闭所有字段的检索
// 'enabled' => 'false'
// ],
// '_source'=>[ // 存储原始文档
// 'enabled' => 'true'
// ],
// 'properties'=> [ //配置数据结构与类型
// 'bank_name'=> [ //字段1
// 'type'=>'string',//类型 string、integer、float、double、boolean、date
// 'index'=> 'analyzed',//索引是否精确值 analyzed not_analyzed 分词器
// ],
// 'bank_code'=> [ //字段2
// 'type'=>'integer',
// ],
// 'name_initial'=> [ //字段3
// 'type'=>'string',
// 'index'=> 'not_analyzed',
// ],
//
// ]
// ],
// 'order000_type' => [ //文档设置 (表)
// 'properties' => [ //属性
// 'bank_name'=> [ //字段名
// 'type'=>'string', //字段类型
// "fielddata"=> true
// ],
// ]
// ],
// ],
//7.x 可以用 但这里设置的是index 不是type 在7.x中存在默认的type _doc type可以不设置 毕竟要删除 一对一的type
// "mappings" => [
// "properties" => [
// 'id' => ["type" => "text", "analyzer" => "ik_smart"],
// 'ids' => ["type" => "text", "analyzer" => "ik_smart"],
// 'member_ids' => ["type" => "text", "analyzer" => "ik_smart"],
// 'name' => ["type" => "text", "analyzer" => "ik_max_word"],
// 'mobile' => ["type" => "text", "analyzer" => "ik_smart"],
// 'pwd' => ["type" => "text", "analyzer" => "ik_smart"],
// 'contact' => ["type" => "text", "analyzer" => "ik_max_word"],
// 'address' => ["type" => "text", "analyzer" => "ik_smart"],
// 'bank_name' => ["type" => "text", "analyzer" => "ik_smart"],
// 'card' => ["type" => "text", "analyzer" => "ik_max_word"],
// 'licence' => ["type" => "text", "analyzer" => "ik_smart"],
// 'brand' => ["type" => "text", "analyzer" => "ik_smart"],
// 'status' => ["type" => "text", "analyzer" => "ik_smart"],
// 'created_at' => ["type" => "text", "analyzer" => "ik_smart"],
// 'updated_at' => ["type" => "text", "analyzer" => "ik_smart"],
// ]
// ]
// ]
];
$res = $client->indices()->create($params); //可以先不设置body
print_r($res);
die;
} catch
(\Exception $e) {
echo "<pre>";
print_r($e->getMessage());
echo "</pre>";
die;
}
}
//索引删除
public function delAction()
{
try {
$client = new EsClientService();
$client = $client->client();
$params = ['index' => 'supplier_index1'];
$response = $client->indices()->delete($params);
print_r($response);
die;
} catch (\Exception $e) {
$e->getMessage();
}
}
//动态创建 实现批量插入
/**
* 要注意当需要设置指定类型时要先创建在设置()可以合到一块
*/
public function CreateAction()
{
try {
$client = new EsClientService();
$client = $client->client();
//创建索引(数据库) 如果存在会报错 第一步
$params = [
'index' => 'newgood9',#index的名字不能是大写和下划线开头
'body' => [
'settings' => [
'number_of_shards' => 2,
'number_of_replicas' => 0
]
]
];
$client->indices()->create($params);
//添加表和字段 第二步
$params = [
'index' => 'newgood9',
'body' => [
// 'articles_type' => [ //开启文档 7.x的版本不在支持设置文档名(type)但是可以
// '_source' => [
// 'enabled' => true
// ],
'properties' => [ //字段
'id' => [
'type' => 'integer'
],
'ids' => [
'type' => 'long'
],
'goods_sn' => [
'type' => 'text',
'fields' => [
'rows' => [
'type' => 'keyword'
]
]
],
'goods_category_ids' => [
'type' => 'long'
],
'title' => [
'type' => 'text',
'fields' => [
'rows' => [
'type' => 'keyword'
]
]
],
'img' => [
'type' => 'text',
'fields' => [
'rows' => [
'type' => 'keyword'
]
]
],
'price' => [
'type' => 'double'
],
'floor_price' => [
'type' => 'double'
],
'ceiling_price' => [
'type' => 'double'
],
'stock' => [
'type' => 'integer'
],
'cquota' => [
'type' => 'integer'
],
'csale' => [
'type' => 'integer'
],
'base_csale' => [
'type' => 'integer'
],
'volume' => [
'type' => 'double'
],
'weight' => [
'type' => 'double'
],
'goods_brand_ids' => [
'type' => 'integer'
],
'postage' => [
'type' => 'double'
],
'shipment_ids' => [
'type' => 'integer'
],
'is_sku' => [
'type' => 'integer'
],
'is_discount' => [
'type' => 'integer'
],
'is_credit' => [
'type' => 'integer'
],
'stock_type' => [
'type' => 'integer'
],
'shelve_timestamp' => [
'type' => 'integer'
],
'is_deleted' => [
'type' => 'integer'
],
'wait_onsale' => [
'type' => 'integer'
],
'onsale' => [
'type' => 'integer'
],
'erp_sn' => [
'type' => 'text',
'fields' => [
'rows' => [
'type' => 'keyword'
]
]
],
'audit_status' => [
'type' => 'integer'
],
'is_supplier' => [
'type' => 'long'
],
'listorder' => [
'type' => 'integer'
],
'commission_percent' => [
'type' => 'text',
'fields' => [
'rows' => [
'type' => 'keyword'
]
]
],
'discount_percent' => [
'type' => 'text',
'fields' => [
'rows' => [
'type' => 'keyword'
]
]
],
'bonus_percent' => [
'type' => 'text',
'fields' => [
'rows' => [
'type' => 'keyword'
]
]
],
'is_rebuy' => [
'type' => 'integer'
],
]
]
// ]
];
$client->indices()->putMapping($params);
//获取数据并批量插入 第三步
$Goods = Goods::init();
$lists = $Goods->getList([], ['id', 'ids', 'goods_sn', 'goods_category_ids', 'title', 'img', 'price', 'floor_price', 'ceiling_price','stock','cquota','csale','base_csale','volume','weight','goods_brand_ids','postage','shipment_ids','is_sku','is_discount','is_credit','stock_type','shelve_at','shelve_timestamp','is_deleted','wait_onsale','onsale','erp_sn','is_supplier','audit_status','listorder','commission_percent','discount_percent','bonus_percent','is_rebuy'], '', 0, 1000);
foreach ($lists as $row) {
$params = [
'id' => 'Goods' . $row['id'],
'index' => 'newgood9',
'body' => [
'id' => $row['id'],
'ids' => $row['ids'],
'goods_sn' => $row['goods_sn'],
'goods_category_ids' => $row['goods_category_ids'],
'title' => $row['title'],
'img' => $row['img'],
'price' => $row['price'],
'floor_price' => $row['floor_price'],
'ceiling_price' => $row['ceiling_price'],
'stock' => $row['stock'],
'cquota' => $row['cquota'],
'csale' => $row['csale'],
'base_csale' => $row['base_csale'],
'volume' => $row['volume'],
'weight' => $row['weight'],
'goods_brand_ids' => $row['goods_brand_ids'],
'postage' => $row['postage'],
'shipment_ids' => $row['shipment_ids'],
'is_sku' => $row['is_sku'],
'is_discount' => $row['is_discount'],
'is_credit' => $row['is_credit'],
'stock_type' => $row['stock_type'],
'shelve_timestamp' => $row['goods_category_ids'],
'is_deleted' => $row['is_deleted'],
'wait_onsale' => $row['wait_onsale'],
'onsale' => $row['onsale'],
'erp_sn' => $row['erp_sn'],
'audit_status' => $row['audit_status'],
'is_supplier' => $row['is_supplier'],
'listorder' => $row['listorder'],
'commission_percent' => $row['commission_percent'],
'discount_percent' => $row['discount_percent'],
'bonus_percent' => $row['bonus_percent'],
'is_rebuy' => $row['is_rebuy'],
]
];
$result = $client->index($params);//这里会自动执行上面屏蔽的内容(创建和设置mapping),但是分析器不确定是否要设置
print_r($result);
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
//批量插入数据
public function esBulsAction()
{
$client = new EsClientService();
$client = $client->client();
// $model = new Payment();
// $lists = $model->getList([], ['id', 'name'], 'id ASC');
$goods = Goods::init();
$lists = $goods->getList([], ['id', 'ids', 'goods_sn', 'supplier_ids', 'goods_category_ids', 'title', 'img', 'price', 'floor_price', 'ceiling_price','stock','cquota','csale','base_csale','volume','weight','goods_brand_ids','postage','shipment_ids','is_sku','is_discount','is_credit','stock_type','shelve_at','shelve_timestamp','unshelve_at','is_deleted','wait_onsale','onsale','onsale_at','erp_sn','is_supplier','audit_status','listorder','audited_at','commission_percent','discount_percent','bonus_percent','is_rebuy'], '', 0, 1000);
$params['body'] = [];
foreach ($lists as $k => $v) {
$params['body'][] = [
'index' => [ #创建
'_index' => 'good',
'_id' => $k,
],
];
$params['body'][] = [
'name' => $v['name'],
];
}
$res = $client->bulk($params);
//
// $params = [
// 'index' => 'my_index',
// 'type' => 'my_type',
// 'body' => [
// 'query' => [
// "exists"=> [
// "field"=>"name" //字段搜索
// ]
// ]
// ]
// ];
// $params = [
// 'index' => 'my_index',
// 'type' => 'my_type',
// 'body' => [
// 'query' => [
// "te"=> [
// "name"=>"支付"
// ]
// ]
// ]
// ];
// $rt = $client->search($params);
// print_r($rt);
}
/**
* 获取指定索引的映射关系
*以下为默认(动态创建时)
* Array
* (
* [supplier_index] => Array
* (
* [mappings] => Array
* (
* [properties] => Array
* (
* [address] => Array //字段名为address
* (
* [type] => text
* [fields] => Array //字段属性设置
* (
* [keyword] => Array
* (
* [type] => keyword
* [ignore_above] => 256
* )
*
* )
*
* )
* )
* )
* )
* )
*/
public function getMappingsAction()
{
$client = new EsClientService();
$client = $client->client();
$params = [
'index' => 'supplier_index3',
];
$res = $client->indices()->getMapping($params);
print_r($res);
die;
}
/**
* 必须先创建索引
* 修改Mappings
* 注意:修改Mappings的API必须要指明type,且只能添加,不能修改已有的属性。
*/
public function putMappingsAction()
{
try {
$client = new EsClientService();
$client = $client->client();
/**
* 可以用
* PUT my_index/_mapping
* {
* "properties": {
* "my_field": {
* "type": "text",
* "fielddata": true
* }
* }
* }
*/
$params = [
'index' => 'supplier1_index',
'type' => 'supplier_type',//必须指明类型名
'include_type_name' => true,
'body' => [
'supplier_type' => [ //开启文档
'_source' => [
'enabled' => true
],
'properties' => [ //字段
'id' => ["type" => "integer", "analyzer" => "ik_smart"],
'ids' => ["type" => "long", "analyzer" => "ik_smart"],
'member_ids' => ["type" => "long", "analyzer" => "ik_smart"],
'name' => ["type" => "text", "analyzer" => "ik_max_word"],
'mobile' => ["type" => "text", "analyzer" => "ik_smart"],
'pwd' => ["type" => "text", "analyzer" => "ik_smart"],
'contact' => ["type" => "text", "analyzer" => "ik_max_word"],
'address' => ["type" => "text", "analyzer" => "ik_smart"],
'bank_name' => ["type" => "text", "analyzer" => "ik_smart"],
'card' => ["type" => "text", "analyzer" => "ik_max_word"],
'licence' => ["type" => "text", "analyzer" => "ik_smart"],
'brand' => ["type" => "text", "analyzer" => "ik_smart"],
'status' => ["type" => "text", "analyzer" => "ik_smart"],
'created_at' => ["type" => "text", "analyzer" => "ik_smart"],//"creationdate":{type":"date","format":"yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"}它还支持时间戳的格式,这里我们用epoch_mills来表示。
'updated_at' => ["type" => "text", "analyzer" => "ik_smart"],
]
]
]
];
$res = $client->indices()->putMapping($params);
print_r($res);
die;
} catch (\Exception $e) {
echo "<pre>";
print_r($e->getMessage());
echo "</pre>";
die;
}
}
public function test2Action()
{
try {
$client = new EsClientService();
$client = $client->client();
$params = [
'index' => 'my_index',
'type' => 'my_type',
'body' => [
'query' => [
"match" => [ //分词模糊查询
"name" => "余付"
]
]
]
];
$rt = $client->search($params);
echo "<pre>";
print_r($rt);
echo "</pre>";
} catch (\Exception $e) {
echo "<pre>";
print_r($e->getMessage());
echo "</pre>";
die;
}
}
public function setBankDataAction()
{
try {
$client = new EsClientService();
$client = $client->client();
$model = new Bank();
$lists = $model->getList([], ['bank_code', 'bank_name', 'name_initial']);
$params['body'] = [];
foreach ($lists as $k => $v) {
$params['body'][] = [
'create' => [ #创建
'_index' => 'order000_index',
'_type' => 'order000_type',
'_id' => $k,
]
];
$params['body'][] = [
'bank_code' => $v['bank_code'],
'bank_name' => $v['bank_name'],
'bank_initial' => $v['bank_initial']
];
}
$res = $client->bulk($params);
// $params = [
// 'index' => 'my_index',
// 'type' => 'my_type',
// 'body' => [
// 'query' => [
// "te"=> [
// "name"=>"支付"
// ]
// ]
// ]
// ];
// $rt = $client->search($params);
print_r($res);
} catch (\Exception $e) {
echo "<pre>";
print_r($e->getMessage());
echo "</pre>";
die;
}
}
//条件查询 should与must不能同时使用,若同时使用,则只有must起作用
public function getDataLikeAction()
{
try {
$client = new EsClientService();
$client = $client->client();
$json = '{
"index":"order00_index",
"type":"order00_type",
"body":{
"query": {
"bool": {
"should":[{"match":{"bank_name": "包"}},{"match":{"name_initial":"A"}}],
"must": {
"match": {
"name_initial":"Z"
}
}
}
}
}
}';
$array = json_decode($json, true);
print_r($array);
//这里的*没用 等同于match查询
// $params = [
// 'index' => 'order00_index',
// 'type' => 'order00_type',
// 'body' => [
// 'query' => [
// 'wildcard' => [
// "bank_name" =>"山*",
// ]
// ]
// ]
// ];
$results = $client->search($array);
print_r($results);
} catch (\Exception $e) {
echo "<pre>";
print_r($e->getMessage());
echo "</pre>";
die;
}
}
/**
* 少量数据分页显示
*/
public function es_searchAction()
{
try {
$client = new EsClientService();
$client = $client->client();
$data["index"] = "supplier_index2";
$data["type"] = "supplier_type";
[$page, $pageSize, $offset] = $this->getPagingParams();
$data["body"] = array(
"query" =>
array("bool" =>
array("must" =>
array("match_all" => new \stdClass())
)
)
);
// pagesize/from
$data["body"]["size"] = $pageSize;
$data["body"]["from"] = ($page - 1) * $pageSize;
$data = $client->search($data);
print_r($data);
} catch (\Exception $e) {
echo "<pre>";
print_r($e->getMessage());
echo "</pre>";
}
}
public function indexrtestAction()
{
$client = new EsClientService();
$client = $client->client();
$page = $_REQUEST['page'] ?? 2;
$size = $_REQUEST['size'] ?? 2;
$searchParams = array(
'index' => 'supplier_index',
'type' => 'supplier_type',
"scroll" => "1m", //增加_scroll_id
"size" => $size,
);
$docs = $client->search($searchParams);
$scroll_id = $docs['_scroll_id'];
$i = 1;
if ($page == 1) {
echo "<pre>";
print_r($docs);
echo "</pre>";
}
while ($i < $page) {
$response = $client->scroll(
array(
"scroll_id" => $scroll_id,
"scroll" => "1m"
)
);
if (count($response['hits']['hits']) > 0) { //判断是否查到了数据
$scroll_id = $response['_scroll_id'];
} else {
break;
}
$i++;
}
echo "<pre>";
print_r($response);
echo "</pre>";
}
public function es_scroll2Action()
{
try {
// Integer $pageNo, Integer pageSize,
$scrollId = "";
$client = new EsClientService();
$client = $client->client();
$data["index"] = "supplier_index2";
$data["type"] = "supplier_type";
$page = $_REQUEST['page'] ?? 2;
$pageSize = $_REQUEST['size'] ?? 2;
// [$page, $pageSize, $offset] = $this->getPagingParams();
if ($page != null && $pageSize != null) {
if ($page < 0) {
$page = 0;
}
}
$scollTimeInMillis = "1m"; // scrollId过期时间
$searchParams = array(
'index' => 'supplier_index',
'type' => 'supplier_type',
"scroll" => '1m', //增加_scroll_id
"size" => $pageSize,
);
$docs = $client->search($searchParams);
$response = $client->scroll(
array(
"scroll_id" => $docs["_scroll_id"],
"scroll" => $scollTimeInMillis
)
);
print_r($response);
die;
foreach ($response as $k => $v) {
$id = $response['hits']['hits'][$k]["_source"]["id"];
echo $id;
}
if (Empty($id)) {
$client->clearScroll(['scrollId' => $docs['scroll_id']]); //无查询结果清除
}
return "结束";
} catch (\Exception $e) {
echo "<pre>";
print_r($e->getMessage());
echo "</pre>";
}
}
//获取指定id的数据
public function getAction()
{
$client = new EsClientService();
$client = $client->client();
$params = [
'index' => 'totalgoods_index9',
'id' => 'totalGoods9'
];
$res = $client->get($params);
print_r($res);
}
/**
* 获取指定id文档中的_sourc中的存储数据,获取到的格式如下:
* Array
* (
* [name] => 微信支付
* )
*/
public function getSourceAction()
{
$client = new EsClientService();
$client = $client->client();
$params = [
'index' => 'totalgoods_index9',
'type' => '_doc',
'id' => 'totalGoods9'
];
$res = $client->getSource($params);//获取指定id的文档中的_source中的数据
print_r($res);
die;
}
//获取所有数据(不设置size,默认只获取到了前十)
public function SearchAction()
{
try {
$client = new EsClientService();
$client = $client->client();
$params = [
'index' => 'totalgoods_index9',
'body' => [
'query' => [
'match_all' => new \stdClass()
],
'size' => 100
]
];
$res = $client->search($params);
print_r($res);
} catch (\Exception $e) {
$e->getMessage();
}
}
//分词 模糊 查询 (不设置size则默认)
public function simpleSearch1Action()
{
try {
$client = new EsClientService();
$client = $client->client();
$params = [
'index' => 'totalgoods_index9',
'type' => '_doc',
'body' => [
'query' => [
"match" => [ //分词模糊查询
"goods_name" => "袜"
]
]
]
];
$rt = $client->search($params);
echo "<pre>";
print_r($rt);
echo "</pre>";
} catch (\Exception $e) {
echo "<pre>";
print_r($e->getMessage());
echo "</pre>";
die;
}
}
//使用Json格式来进行查询
public function useJsonGetAction()
{
$client = new EsClientService();
$client = $client->client();
// $json = '{
// "query" : {
// "match" : {
// "bank_name" : "银行"
// }
// }
// }';
//两个字段进行匹配,其中一个字段有这个文档就满足的话,使用multi_match
// $json = '{
// "query": {
// "multi_match": {
// "query" : "201908150000000893",
// "fields" : ["goods_name", "outer_goods_order_sn"]
// }
// }
// }';
$json = '{
"query": {
"bool": {
"should": [
{"match": {"goods_name": "女丝袜"}},
{"term": {"outer_goods_order_sn": "201908150000000893"}
}],
"filter": {
"range": {
"order_ids": {
"gt": "321042695"
}
}
}
}
}
}';
$params = [
'index' => 'totalgoods_index9',
'type' => '_doc',
'body' => $json
];
$results = $client->search($params);
print_r($results);
}
//范围获取
public function getDataRangeAction()
{
try {
$client = new EsClientService();
$client = $client->client();
//
// GET /my_index/_search
//{
// "sort" : [
// { "post_date" : {"order" : "asc"}},
//
// { "name" : "desc" },
// { "age" : "desc" },
//
// ],
// "query" : {
// "term" : { "user" : "kimchy" }//这里要是不能精确查询就要用match
// }
//}
// $json = '{
// "query": {
// "bool": {
// "must": {
// "match": {
// "bank_name": "toothbrush"
// }
// },
// "filter": {
// "range": {
// "name_initial": {
// "gt": "C",
// "lt": "V"
// }
// }
// }
// }
// }
// }';
$params = [
'index' => 'supplier_index2',
'type' => 'supplier_type',
'body' => [
'query' => [
'bool' => [
'must' => [
'match' => [
'name' => '店',
]
],
// 'filter'=>[
// 'range'=>[
// 'name_initial'=>[
// 'gt'=>'C',
// 'lt'=>'V'
// ]
// ]
// ]
]
],
"sort" => [
// // "_score"=>"asc" //按照_score由小到大排序
// "_score"=>"desc"
// "sort" :{ "name" :{"order": "desc"}} 这里要将text类型的属性"fielddata": true
// "_source"=>[//不行
// "id"=>"desc"
// ]
]
]
];
$results = $client->search($params);
print_r($results);
die;
} catch (\Exception $e) {
echo "<pre>";
print_r($e->getMessage());
echo "</pre>";
die;
}
}
}