Перейти к навигации

How do I compare recent search trends for Xiaohongshu keyword candidates?

To compare recent search trends for several Xiaohongshu keyword candidates, call xiaohongshu.pgy.get_keyword_daily once per term and align the searchScore values by shared dates. Three topic ideas take three requests and give three series. Use the index to spot changes, then read related notes and comments to decide what to cover.

For example, if the score for “sunscreen” rose over two weeks, look for the situations and questions readers mention. Before comparing the two weeks, check that each date has a score, and keep note counts and search-user counts in separate columns.

Choose the material for the question

QuestionCapability
How does it change by day?data:xiaohongshu.pgy.get_keyword_daily
Do I need an overview?data:xiaohongshu.pgy.get_keyword_stat
Which nearby directions should I investigate?data:xiaohongshu.pgy.get_keyword_related
What does the search box suggest?Search suggestions

get_keyword_daily, get_keyword_stat and get_keyword_related each take one search_word. Daily observations for three terms take three requests. Add overview or related-term requests only when needed; the three actions return three different results.

Save a trend for one term

Replace the example term in the daily request with your candidate:

curl -sS https://api.beatapi.io/v1/social-data/call \
-H "Authorization: Bearer $BEATAPI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"action":"xiaohongshu.pgy.get_keyword_daily","params":{"search_word":"面膜"}}' \
-o xiaohongshu-keyword-daily.json

xiaohongshu.pgy.get_keyword_daily takes no date interval, month or keyword array. Use the window actually returned and record the collection time for each term. Keep dateKey, searchScore, noteNum and userNum from data.data.dailyData[] in separate columns, and do not derive people counts from the index.

Make three checks before interpreting a chart

  1. Date coverage: missing dates stay missing and appear as chart gaps, not zeroes. The latest returned date may not be today.
  2. Comparability: compare common dates and the same index definition across terms instead of dividing totals from different windows.
  3. Discussion context: treat rising terms as candidates for content research and read the actual questions. Interest alone explains neither the cause nor conversion.

The local helper pgy_daily.py below compares means only when both consecutive seven-day windows have complete index data. summary.json records the windows, missing dates and baseline state; daily.csv keeps the daily values next to the original response.

For example, a teammate wants to compare hydrating and cleansing masks. Save a daily result for each term. If the latest dates differ, use the two weeks that both results cover. Keep the term, the windows, the daily scores and the missing dates. If only one week is complete, report that week’s values first.

Plan retrieval costs

Choose the number of terms and estimate the cost with the current daily-query pricing. Charting, comparing saved periods and writing a brief happen locally, so revising a chart needs no new request.

Export a daily evidence table and compare two complete weeks

BeatAPI preserves the Pugongying envelope directly under data, so xiaohongshu.pgy.get_keyword_daily returns dateKey, searchScore, noteNum, and userNum inside data.data.dailyData[]. Keep the index, note count, and searcher count in separate columns; do not derive people counts from the index. The target platform selects the returned date window, and the window is not guaranteed to be exactly 90 days.

Save each candidate’s response and export each response into a separate directory. Three terms take three daily requests; overviews, related terms, and note or comment research are separate choices. A request record looks like this:

{"action":"xiaohongshu.pgy.get_keyword_daily","params":{"search_word":"防晒霜"},"collected_at":"2026-11-16T10:00:00Z"}

Save the script below as pgy_daily.py. pgy_daily.py accepts date labels in YYYY-MM-DD or YYYYMMDD form (including integer YYYYMMDD); other formats stop for inspection instead of guessing a timezone or unit. Numeric values must be plain non-negative numbers, and note and searcher counts must be whole numbers. Missing values stay missing. pgy_daily.py sorts valid dates, rejects duplicate days, reports gaps, and compares the mean index of two adjacent seven-day windows only when all 14 dates have a searchScore. These validation rules belong to pgy_daily.py; future platform responses may use other representations.

import csv,datetime,decimal,hashlib,json,pathlib,re,sys
source,manifest,target=map(pathlib.Path,sys.argv[1:4])
request=json.loads(manifest.read_text(encoding="utf-8"));params=request.get("params")
if request.get("action")!="xiaohongshu.pgy.get_keyword_daily" or not isinstance(params,dict) or set(params)!={"search_word"}:raise ValueError("Record the exact daily keyword request")
keyword=params["search_word"]
if not isinstance(keyword,str) or not keyword.strip() or not 1<=len(keyword)<=100:raise ValueError("One nonempty keyword required")
stamp=request["collected_at"]
if datetime.datetime.fromisoformat(stamp.replace("Z","+00:00")).tzinfo is None:raise ValueError("Timezone required")
raw=source.read_bytes();r=json.loads(raw)
if r.get("status")!="succeeded" or r.get("action")!=request["action"]:raise ValueError("Expected successful keyword response")
rid=r.get("request_id")
if not isinstance(rid,str) or not rid.strip():raise ValueError("request_id required")
envelope=r.get("data")
if not isinstance(envelope,dict) or envelope.get("success") is not True:raise ValueError("PGY business failure")
data=envelope.get("data")
if not isinstance(data,dict) or not isinstance(data.get("dailyData"),list):raise ValueError("Expected non-null dailyData array")
def day(value):
if type(value) is int:value=str(value)
if not isinstance(value,str):raise ValueError("Unsupported dateKey")
if re.fullmatch(r"[0-9]{8}",value):return datetime.datetime.strptime(value,"%Y%m%d").date()
if re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}",value):return datetime.date.fromisoformat(value)
raise ValueError("Helper accepts YYYYMMDD or YYYY-MM-DD date labels only")
def metric(value,integer=False):
if value is None:return None
if type(value) not in (str,int,float):raise ValueError("Unsupported numeric value")
text=str(value)
if not re.fullmatch(r"[0-9]+(?:\.[0-9]+)?",text):raise ValueError("Unsupported formatted number")
number=decimal.Decimal(text)
if integer and number!=number.to_integral_value():raise ValueError("Count must be whole")
return number
points={}
for item in data["dailyData"]:
if not isinstance(item,dict):raise ValueError("Invalid daily point")
date=day(item.get("dateKey"))
if date in points:raise ValueError("Duplicate day; inspect before merging")
points[date]={"date":date.isoformat(),"dateKey":item["dateKey"],
"searchScore":metric(item.get("searchScore")),"noteNum":metric(item.get("noteNum"),True),
"userNum":metric(item.get("userNum"),True)}
summary={"keyword":keyword,"request_id":rid,"collected_at":stamp,"source_sha256":hashlib.sha256(raw).hexdigest(),
"returned_days":len(points),"missing_dates":[],"comparison_state":"insufficient_data",
"comparison":"Two adjacent seven-day averages ending at the latest returned date label; not an official period-over-period metric",
"date_scope":"Returned date labels; no timezone conversion or guaranteed three-month coverage"}
if points:
first,last=min(points),max(points);summary.update({"first_date":first.isoformat(),"last_date":last.isoformat()})
if (last-first).days>3660:raise ValueError("Unexpected date span; inspect source")
summary["missing_dates"]=[(first+datetime.timedelta(days=i)).isoformat() for i in range((last-first).days+1) if first+datetime.timedelta(days=i) not in points]
dates=[last-datetime.timedelta(days=i) for i in range(14)]
if all(date in points and points[date]["searchScore"] is not None for date in dates):
current=sum(points[date]["searchScore"] for date in dates[:7])/7
previous=sum(points[date]["searchScore"] for date in dates[7:])/7
summary.update({"recent_7d_mean":str(current),"previous_7d_mean":str(previous),"mean_change":str(current-previous),
"relative_change":None if previous==0 else str((current-previous)/previous),
"comparison_state":"zero_baseline" if previous==0 else "computed"})
def cell(value):
if value is None:return ""
text=str(value)
return "'"+text if text.lstrip().startswith(("=","+","-","@")) or text.startswith(("\t","\r","\n")) else text
target.mkdir()
with (target/"daily.csv").open("x",encoding="utf-8-sig",newline="") as output:
writer=csv.DictWriter(output,fieldnames=["keyword","date","dateKey","searchScore","noteNum","userNum","request_id","collected_at"]);writer.writeheader()
for date in sorted(points):writer.writerow({key:cell(value) for key,value in {"keyword":keyword,**points[date],"request_id":rid,"collected_at":stamp}.items()})
(target/"raw-response.json").write_bytes(raw)
(target/"summary.json").write_text(json.dumps(summary,ensure_ascii=False,indent=2),encoding="utf-8")
print(str(target/"daily.csv"))

Run python3 pgy_daily.py xiaohongshu-keyword-daily.json keyword-request.json keyword-review-1. Open summary.json before charting the date and searchScore columns of daily.csv. Gaps are not zeroes and stay as chart gaps. The raw dateKey values and the original JSON stay available for verification.

The two-week comparison ends at the latest returned date, which may not be today. relative_change is a fraction, not a percentage; a zero previous mean yields null and zero_baseline. The locally calculated mean change is not an official platform period comparison and not a conversion rate, and one short window does not establish seasonality. Compare several terms only on shared returned dates with the same index definition, never against another platform’s index. Check rising candidates with the real note and comment evidence workflow before choosing a brief.