1. 程式人生 > >ElasticSearch巢狀查詢以及注意事項

ElasticSearch巢狀查詢以及注意事項

es實體 

@Data
@Document(indexName = "indexdemo", type = "typedemo", shards = 3, replicas = 1)
public class TmsWaybillEsEntity {
    /**
     * 主鍵id
     */
    @Id
    private Long id;

    private String waybillNo;

    private String orderNo;

    private Long orderId;

    @Field(type = FieldType.Nested)
    private List<TmsWaybillDispatcherInfoEsEntity> dispatcherBills;

}

 

@Data
public class TmsWaybillDispatcherInfoEsEntity {
    
    private Long dispatcherBillId;
    
    private String dispatcherBillNo;
    
    private Byte waybillType;
    
    private String snapDriverName;
   
    private String snapDriverPhone;
 
    private String snapTruckPlateNumber;

}

 

 

建立索引和對映

    public void createWaybillIndex(){

        if(waybillEsTemplate.indexExists(TmsWaybillEsEntity.class)){
            log.info("運單索引已經存在,無需建立");
        }else{
            boolean createResult = waybillEsTemplate.createIndex(TmsWaybillEsEntity.class);
            waybillEsTemplate.putMapping(TmsWaybillEsEntity.class);
            waybillEsTemplate.refresh(TmsWaybillEsEntity.class);
            log.info("建立運單索引的結果:{}", createResult);
        }

    }

 

巢狀查詢,kibana --> Dev Tools

GET /indexdemo/typedemo/_search
{
	"query": {
		"bool": {
			"must": [{
					"term": {
						"companyId": {
							"value": 965006065496327513,
							"boost": 1.0
						}
					}
				},
				{
					"nested": {
						"query": {
							"bool": {
								"must": [{
									"wildcard": {
										"dispatcherBills.dispatcherBillNo.keyword": {
											"value": "*P101454019050700013*",
											"boost": 1.0
										}
									}
								}],
								"disable_coord": false,
								"adjust_pure_negative": true,
								"boost": 1.0
							}
						},
						"path": "dispatcherBills",
						"score_mode": "max", 
						"ignore_unmapped": false,
						"boost": 1.0
					}
				},
				{
					"nested": {
						"query": {
							"bool": {
								"must": [{
									"term": {
										"dispatcherBills.snapDriverName.keyword": {
											"value": "smxc",
											"boost": 1.0
										}
									}
								}],
								"disable_coord": false,
								"adjust_pure_negative": true,
								"boost": 1.0
							}
						},
						"path": "dispatcherBills",
						"score_mode": "max", 
						"ignore_unmapped": false,
						"boost": 1.0
					}
				}
			],
			"disable_coord": false,
			"adjust_pure_negative": true,
			"boost": 1.0
		}
	}

}

注意事項, 分片數量和副本數量要和運維的同事配置的一