Skip to content

Instantly share code, notes, and snippets.

@waycroft
Last active October 17, 2021 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waycroft/1c867deea54ef3b6112d6947c22eefa0 to your computer and use it in GitHub Desktop.
Save waycroft/1c867deea54ef3b6112d6947c22eefa0 to your computer and use it in GitHub Desktop.
Utility script for creating a Mixpanel $merge event to merge user profiles that share the same email.
// please reference https://developer.mixpanel.com/reference/identities#identity-merge first, as this is an irreversible operation!!!
// also address the TODOs found before running
import fetch from 'node-fetch';
var csv = require('node-csv').createParser();
interface DuplicatePairDict {
[email: string]: [string, string]
}
function returnDuplicates(data: string[][]): DuplicatePairDict {
let flag = {};
let duplicates: DuplicatePairDict = {};
for (let row = 0;row < data.length;row++) {
// TODO: this skips the default header line––adjust this if/else if you don't have it or deleted it
if (row === 0) {
continue;
} else {
// TODO: make sure that you change the selectors here based on your .csv export 👇
const email = data[row][5];
const distinctId = data[row][0];
if (!flag[email]) {
flag[email] = distinctId;
} else {
const otherId = flag[email];
duplicates[email] = [distinctId, otherId];
}
}
}
return duplicates;
}
async function merge(idList: string[]) {
const url = 'https://api.mixpanel.com/import?strict=1';
const options = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
// TODO:
Authorization: 'Basic YOUR_MIXPANEL_API_SECRET_AFTER_INSERTING_INTO_INTERACTIVE_API'
},
body: JSON.stringify([
{
event: '$merge',
properties: {
$distinct_ids: idList
}
}
])
};
try {
let res = (await fetch(url, options)).json();
return res;
} catch(e) {
console.error(e)
}
}
// TODO:
csv.parseFile('YOUR_USER_PROFILE_EXPORT.csv', async function(err: Error, data: string[][]) {
if (err) {
console.error(err);
return
} else {
// TODO: Do a dry run first and see which emails will be merged, and then uncomment the loop below to actually run:
const emailsToMerge = returnDuplicates(data);
console.log(emailsToMerge);
/* for (let email of Object.keys(emailsToMerge)) {
let mergeOp = await merge(emailsToMerge[email]);
console.log('merged $distinct_ids belonging to', email, ':', emailsToMerge[email], '\n', mergeOp);
} */
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment