MySQL LIKE 查询无法做到真正的全文搜索——不能处理同义词(「手机」vs「智能手机」)、无法实现拼音搜索、搜索结果无相关度排序。Elasticsearch 是当前最成熟的分布式全文搜索引擎,本文在香港服务器上为独立站商品库搭建完整的搜索能力。
一、Docker 部署 Elasticsearch + Kibana
<code"># /opt/elasticsearch/docker-compose.yml
version: '3.8'
services:
elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:8.15.0
container_name: elasticsearch
restart: unless-stopped
environment:
- discovery.type=single-node # 单节点模式
- ES_JAVA_OPTS=-Xms2g -Xmx2g # JVM 堆内存(建议为可用内存的一半)
- xpack.security.enabled=true
- ELASTIC_PASSWORD=your_elastic_pass
- xpack.security.http.ssl.enabled=false # 内网不需要 SSL
ports:
- "127.0.0.1:9200:9200"
volumes:
- es_data:/usr/share/elasticsearch/data
- ./plugins:/usr/share/elasticsearch/plugins # IK 分词器挂载目录
ulimits:
memlock:
soft: -1
hard: -1
kibana:
image: docker.elastic.co/kibana/kibana:8.15.0
container_name: kibana
restart: unless-stopped
ports:
- "127.0.0.1:5601:5601"
environment:
ELASTICSEARCH_HOSTS: http://elasticsearch:9200
ELASTICSEARCH_USERNAME: kibana_system
ELASTICSEARCH_PASSWORD: your_elastic_pass
depends_on:
- elasticsearch
volumes:
es_data:
<code"># 安装 IK 中文分词器(必须与 ES 版本一致)
mkdir -p /opt/elasticsearch/plugins/ik
cd /opt/elasticsearch/plugins/ik
wget https://github.com/infinilabs/analysis-ik/releases/download/v8.15.0/elasticsearch-analysis-ik-8.15.0.zip
unzip elasticsearch-analysis-ik-8.15.0.zip
rm elasticsearch-analysis-ik-8.15.0.zip
# 重启 ES 使插件生效
docker compose restart elasticsearch
# 验证 IK 分词器
curl -X POST "http://localhost:9200/_analyze?pretty" \
-H "Content-Type: application/json" \
-u elastic:your_elastic_pass \
-d '{"analyzer": "ik_max_word", "text": "小米手机性价比高"}'
二、商品索引设计
<code">// 创建商品索引(含中文分词 + 拼音 + 自动补全)
PUT /products
{
"settings": {
"number_of_shards": 1,
"number_of_replicas": 0,
"analysis": {
"analyzer": {
// 中文全文搜索分析器
"ik_smart_analyzer": {
"type": "custom",
"tokenizer": "ik_smart",
"filter": ["lowercase", "synonym_filter"]
},
// 自动补全分析器(前缀匹配)
"completion_analyzer": {
"type": "custom",
"tokenizer": "ik_max_word",
"filter": ["lowercase"]
}
},
"filter": {
// 同义词配置
"synonym_filter": {
"type": "synonym",
"synonyms": [
"手机, 智能手机, 移动电话",
"耳机, 耳麦, 听筒",
"充电器, 充电头, 电源适配器"
]
}
}
}
},
"mappings": {
"properties": {
"product_id": { "type": "keyword" },
"title": {
"type": "text",
"analyzer": "ik_smart_analyzer",
"search_analyzer": "ik_smart_analyzer",
"fields": {
"raw": { "type": "keyword" }, // 精确匹配
"suggest": { "type": "completion" } // 自动补全
}
},
"description": { "type": "text", "analyzer": "ik_smart_analyzer" },
"category": { "type": "keyword" },
"brand": { "type": "keyword" },
"price": { "type": "float" },
"stock": { "type": "integer" },
"rating": { "type": "float" },
"review_count": { "type": "integer" },
"images": { "type": "keyword", "index": false },
"tags": { "type": "keyword" },
"is_active": { "type": "boolean" },
"created_at": { "type": "date" }
}
}
}
三、搜索查询(Python)
<code">from elasticsearch import Elasticsearch
es = Elasticsearch(
"http://localhost:9200",
basic_auth=("elastic", "your_elastic_pass")
)
def search_products(
query: str,
category: str = None,
price_min: float = None,
price_max: float = None,
page: int = 1,
page_size: int = 20
) -> dict:
"""
全文搜索商品(含相关度排序 + 筛选 + 高亮)
"""
must_clauses = []
filter_clauses = [{"term": {"is_active": True}}]
# 全文搜索(标题权重更高)
if query:
must_clauses.append({
"multi_match": {
"query": query,
"fields": ["title^3", "description^1", "tags^2"],
"type": "best_fields",
"operator": "or",
"minimum_should_match": "60%"
}
})
# 分类筛选
if category:
filter_clauses.append({"term": {"category": category}})
# 价格区间筛选
price_range = {}
if price_min is not None:
price_range["gte"] = price_min
if price_max is not None:
price_range["lte"] = price_max
if price_range:
filter_clauses.append({"range": {"price": price_range}})
body = {
"query": {
"function_score": {
"query": {
"bool": {
"must": must_clauses or [{"match_all": {}}],
"filter": filter_clauses
}
},
# 评分加权:评分高、评论多的商品排名更靠前
"functions": [
{"field_value_factor": {"field": "rating", "factor": 0.3}},
{"field_value_factor": {"field": "review_count", "modifier": "log1p", "factor": 0.1}},
],
"boost_mode": "sum"
}
},
# 搜索关键词高亮
"highlight": {
"fields": {
"title": {"number_of_fragments": 0},
"description": {"fragment_size": 150, "number_of_fragments": 2}
},
"pre_tags": [""],
"post_tags": [""]
},
"from": (page - 1) * page_size,
"size": page_size,
# 聚合:用于筛选面板
"aggs": {
"categories": {"terms": {"field": "category", "size": 20}},
"price_range": {"range": {"field": "price", "ranges": [
{"to": 100}, {"from": 100, "to": 500}, {"from": 500}
]}}
}
}
result = es.search(index="products", body=body)
return {
"total": result["hits"]["total"]["value"],
"products": [
{**hit["_source"], "highlight": hit.get("highlight", {})}
for hit in result["hits"]["hits"]
],
"aggregations": result.get("aggregations", {})
}
def autocomplete(prefix: str, size: int = 8) -> list[str]:
"""搜索框自动补全"""
result = es.search(index="products", body={
"suggest": {
"product_suggest": {
"prefix": prefix,
"completion": {
"field": "title.suggest",
"size": size,
"skip_duplicates": True
}
}
},
"_source": False
})
return [
opt["text"]
for opt in result["suggest"]["product_suggest"][0]["options"]
]
四、MySQL → Elasticsearch 数据同步
<code"># 使用 Logstash 实现 MySQL 数据同步到 ES(增量同步)
# /opt/logstash/pipeline/mysql-to-es.conf
input {
jdbc {
jdbc_driver_library => "/opt/logstash/mysql-connector-j-8.2.0.jar"
jdbc_driver_class => "com.mysql.cj.jdbc.Driver"
jdbc_connection_string => "jdbc:mysql://localhost:3306/mydb"
jdbc_user => "logstash"
jdbc_password => "logstash_pass"
# 每5分钟同步一次(增量:只同步更新时间大于上次同步时间的记录)
schedule => "*/5 * * * *"
statement => "SELECT * FROM products WHERE updated_at > :sql_last_value"
use_column_value => true
tracking_column => "updated_at"
tracking_column_type => "timestamp"
}
}
output {
elasticsearch {
hosts => ["http://localhost:9200"]
index => "products"
document_id => "%{product_id}"
user => "elastic"
password => "your_elastic_pass"
}
}
五、总结
Elasticsearch + IK 中文分词器为独立站提供了媲美淘宝搜索的体验:同义词扩展、拼音支持、相关度排序、搜索高亮、自动补全一应俱全。香港服务器的 SSD 存储保证 ES 的索引读写性能,8核16G 配置可以支撑千万级商品的秒级搜索响应。
